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
+280
View File
@@ -0,0 +1,280 @@
<?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/>.
/**
* External rating functions unit tests
*
* @package core_rating
* @category external
* @copyright 2015 Costantino Cito <ccito@cvaconsulting.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_rating;
use core_external\external_api;
use core_rating_external;
use externallib_advanced_testcase;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
require_once($CFG->dirroot . '/rating/lib.php');
/**
* External rating functions unit tests
*
* @package core_rating
* @category external
* @copyright 2015 Costantino Cito <ccito@cvaconsulting.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class externallib_test extends externallib_advanced_testcase {
/** @var \stdClass course record. */
protected $course;
/** @var \stdClass user record. */
protected $student1;
/** @var \stdClass user record. */
protected $teacher1;
/** @var \stdClass user record. */
protected $student2;
/** @var \stdClass user record. */
protected $teacher2;
/** @var \stdClass user record. */
protected $student3;
/** @var \stdClass user record. */
protected $teacher3;
/** @var \stdClass activity record. */
protected $forum;
/** @var \stdClass activity record. */
protected $discussion;
/** @var int context instance ID. */
protected $contextid;
/** @var \stdClass forum post. */
protected $post;
/** @var \stdClass a fieldset object, false or exception if error not found. */
protected $studentrole;
/** @var \stdClass a fieldset object, false or exception if error not found. */
protected $teacherrole;
/*
* Set up for every test
*/
public function setUp(): void {
global $DB;
$this->resetAfterTest();
$this->course = self::getDataGenerator()->create_course();
$this->student1 = $this->getDataGenerator()->create_user();
$this->student2 = $this->getDataGenerator()->create_user();
$this->teacher1 = $this->getDataGenerator()->create_user();
$this->teacher2 = $this->getDataGenerator()->create_user();
$this->teacher3 = $this->getDataGenerator()->create_user();
$this->studentrole = $DB->get_record('role', array('shortname' => 'student'));
$this->teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
unassign_capability('moodle/site:accessallgroups', $this->teacherrole->id);
$this->getDataGenerator()->enrol_user($this->student1->id, $this->course->id, $this->studentrole->id);
$this->getDataGenerator()->enrol_user($this->student2->id, $this->course->id, $this->studentrole->id);
$this->getDataGenerator()->enrol_user($this->teacher1->id, $this->course->id, $this->teacherrole->id);
$this->getDataGenerator()->enrol_user($this->teacher2->id, $this->course->id, $this->teacherrole->id);
$this->getDataGenerator()->enrol_user($this->teacher3->id, $this->course->id, $this->teacherrole->id);
// Create the forum.
$record = new \stdClass();
$record->introformat = FORMAT_HTML;
$record->course = $this->course->id;
// Set Aggregate type = Average of ratings.
$record->assessed = RATING_AGGREGATE_AVERAGE;
$record->scale = 100;
$this->forum = self::getDataGenerator()->create_module('forum', $record);
$this->contextid = \context_module::instance($this->forum->cmid)->id;
// Add discussion to the forums.
$record = new \stdClass();
$record->course = $this->course->id;
$record->userid = $this->student1->id;
$record->forum = $this->forum->id;
$this->discussion = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record);
// Retrieve the first post.
$this->post = $DB->get_record('forum_posts', array('discussion' => $this->discussion->id));
}
/**
* Test get_item_ratings
*/
public function test_get_item_ratings(): void {
global $DB;
// Rete the discussion as teacher1.
$rating1 = new \stdClass();
$rating1->contextid = $this->contextid;
$rating1->component = 'mod_forum';
$rating1->ratingarea = 'post';
$rating1->itemid = $this->post->id;
$rating1->rating = 90;
$rating1->scaleid = 100;
$rating1->userid = $this->teacher1->id;
$rating1->timecreated = time();
$rating1->timemodified = time();
$rating1->id = $DB->insert_record('rating', $rating1);
// Rete the discussion as teacher2.
$rating2 = new \stdClass();
$rating2->contextid = $this->contextid;
$rating2->component = 'mod_forum';
$rating2->ratingarea = 'post';
$rating2->itemid = $this->post->id;
$rating2->rating = 95;
$rating2->scaleid = 100;
$rating2->userid = $this->teacher2->id;
$rating2->timecreated = time() + 1;
$rating2->timemodified = time() + 1;
$rating2->id = $DB->insert_record('rating', $rating2);
// Delete teacher2, we must still receive the ratings.
delete_user($this->teacher2);
// Teachers can see all the ratings.
$this->setUser($this->teacher1);
$ratings = core_rating_external::get_item_ratings('module', $this->forum->cmid, 'mod_forum', 'post', $this->post->id, 100, '');
// We need to execute the return values cleaning process to simulate the web service server.
$ratings = external_api::clean_returnvalue(core_rating_external::get_item_ratings_returns(), $ratings);
$this->assertCount(2, $ratings['ratings']);
$indexedratings = array();
foreach ($ratings['ratings'] as $rating) {
$indexedratings[$rating['id']] = $rating;
}
$this->assertEquals($rating1->rating.' / '.$rating1->scaleid, $indexedratings[$rating1->id]['rating']);
$this->assertEquals($rating2->rating.' / '.$rating2->scaleid, $indexedratings[$rating2->id]['rating']);
$this->assertEquals($rating1->userid, $indexedratings[$rating1->id]['userid']);
$this->assertEquals($rating2->userid, $indexedratings[$rating2->id]['userid']);
// Student can see ratings.
$this->setUser($this->student1);
$ratings = core_rating_external::get_item_ratings('module', $this->forum->cmid, 'mod_forum', 'post', $this->post->id, 100, '');
// We need to execute the return values cleaning process to simulate the web service server.
$ratings = external_api::clean_returnvalue(core_rating_external::get_item_ratings_returns(), $ratings);
$this->assertCount(2, $ratings['ratings']);
// Invalid item.
try {
$ratings = core_rating_external::get_item_ratings('module', $this->forum->cmid, 'mod_forum', 'post', 0, 100, '');
$this->fail('Exception expected due invalid itemid.');
} catch (\moodle_exception $e) {
$this->assertEquals('invalidrecord', $e->errorcode);
}
// Invalid area.
try {
$ratings = core_rating_external::get_item_ratings('module', $this->forum->cmid, 'mod_forum', 'xyz', $this->post->id, 100, '');
$this->fail('Exception expected due invalid rating area.');
} catch (\moodle_exception $e) {
$this->assertEquals('invalidratingarea', $e->errorcode);
}
// Invalid context. invalid_parameter_exception.
try {
$ratings = core_rating_external::get_item_ratings('module', 0, 'mod_forum', 'post', $this->post->id, 100, '');
$this->fail('Exception expected due invalid context.');
} catch (\invalid_parameter_exception $e) {
$this->assertEquals('invalidparameter', $e->errorcode);
}
// Test for groupmode.
set_coursemodule_groupmode($this->forum->cmid, SEPARATEGROUPS);
$group = $this->getDataGenerator()->create_group(array('courseid' => $this->course->id));
groups_add_member($group, $this->teacher1);
$this->discussion->groupid = $group->id;
$DB->update_record('forum_discussions', $this->discussion);
// Error for teacher3 and 2 ratings for teacher1 should be returned.
$this->setUser($this->teacher1);
$ratings = core_rating_external::get_item_ratings('module', $this->forum->cmid, 'mod_forum', 'post', $this->post->id, 100, '');
// We need to execute the return values cleaning process to simulate the web service server.
$ratings = external_api::clean_returnvalue(core_rating_external::get_item_ratings_returns(), $ratings);
$this->assertCount(2, $ratings['ratings']);
$this->setUser($this->teacher3);
try {
$ratings = core_rating_external::get_item_ratings('module', $this->forum->cmid, 'mod_forum', 'post', $this->post->id, 100, '');
$this->fail('Exception expected due invalid group permissions.');
} catch (\moodle_exception $e) {
$this->assertEquals('noviewrate', $e->errorcode);
}
}
/**
* Test add_rating
*/
public function test_add_rating(): void {
$this->setUser($this->teacher1);
// First rating of 50.
$rating = core_rating_external::add_rating('module', $this->forum->cmid, 'mod_forum', 'post', $this->post->id, 100,
50, $this->student1->id, RATING_AGGREGATE_AVERAGE);
// We need to execute the return values cleaning process to simulate the web service server.
$rating = external_api::clean_returnvalue(core_rating_external::add_rating_returns(), $rating);
$this->assertTrue($rating['success']);
$this->assertEquals(50, $rating['aggregate']);
$this->assertEquals(1, $rating['count']);
// New different rate (it will replace the existing one).
$rating = core_rating_external::add_rating('module', $this->forum->cmid, 'mod_forum', 'post', $this->post->id, 100,
100, $this->student1->id, RATING_AGGREGATE_AVERAGE);
$rating = external_api::clean_returnvalue(core_rating_external::add_rating_returns(), $rating);
$this->assertTrue($rating['success']);
$this->assertEquals(100, $rating['aggregate']);
$this->assertEquals(1, $rating['count']);
// Rate as other user.
$this->setUser($this->teacher2);
$rating = core_rating_external::add_rating('module', $this->forum->cmid, 'mod_forum', 'post', $this->post->id, 100,
50, $this->student1->id, RATING_AGGREGATE_AVERAGE);
$rating = external_api::clean_returnvalue(core_rating_external::add_rating_returns(), $rating);
$this->assertEquals(75, $rating['aggregate']);
$this->assertEquals(2, $rating['count']);
// Try to rate my own post.
$this->setUser($this->student1);
$this->expectException('moodle_exception');
$this->expectExceptionMessage(get_string('ratepermissiondenied', 'rating'));
$rating = core_rating_external::add_rating('module', $this->forum->cmid, 'mod_forum', 'post', $this->post->id, 100,
100, $this->student1->id, RATING_AGGREGATE_AVERAGE);
}
}
+442
View File
@@ -0,0 +1,442 @@
<?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 the core_rating implementation of the Privacy API.
*
* @package core_rating
* @category test
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_rating\privacy;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/rating/lib.php');
use core_rating\privacy\provider;
use core_privacy\local\request\writer;
/**
* Unit tests for the core_rating implementation of the Privacy API.
*
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider_test extends \core_privacy\tests\provider_testcase {
/**
* Rate something as a user.
*
* @param int $userid
* @param string $component
* @param string $ratingarea
* @param int $itemid
* @param \context $context
* @param string $score
*/
protected function rate_as_user($userid, $component, $ratingarea, $itemid, $context, $score) {
// Rate the courses.
$rm = new \rating_manager();
$ratingoptions = (object) [
'component' => $component,
'ratingarea' => $ratingarea,
'scaleid' => 100,
];
// Rate all courses as u1, and the course category too..
$ratingoptions->itemid = $itemid;
$ratingoptions->userid = $userid;
$ratingoptions->context = $context;
$rating = new \rating($ratingoptions);
$rating->update_rating($score);
}
/**
* Ensure that the get_sql_join function returns valid SQL which returns the correct list of rated itemids.
*/
public function test_get_sql_join(): void {
global $DB;
$this->resetAfterTest();
$course1 = $this->getDataGenerator()->create_course();
$course2 = $this->getDataGenerator()->create_course();
$course3 = $this->getDataGenerator()->create_course();
$u1 = $this->getDataGenerator()->create_user();
$u2 = $this->getDataGenerator()->create_user();
$u3 = $this->getDataGenerator()->create_user();
// Rate the courses.
$rm = new \rating_manager();
$ratingoptions = (object) [
'component' => 'core_course',
'ratingarea' => 'course',
'scaleid' => 100,
];
// Rate all courses as u1, and something else in the same context.
$this->rate_as_user($u1->id, 'core_course', 'course', $course1->id, \context_course::instance($course1->id), 25);
$this->rate_as_user($u1->id, 'core_course', 'course', $course2->id, \context_course::instance($course2->id), 50);
$this->rate_as_user($u1->id, 'core_course', 'course', $course3->id, \context_course::instance($course3->id), 75);
$this->rate_as_user($u1->id, 'core_course', 'files', $course3->id, \context_course::instance($course3->id), 99);
// Rate course2 as u2, and something else in a different context/component..
$this->rate_as_user($u2->id, 'core_course', 'course', $course2->id, \context_course::instance($course2->id), 90);
$this->rate_as_user($u2->id, 'user', 'user', $u3->id, \context_user::instance($u3->id), 10);
// Return any course which the u1 has rated.
// u1 rated all three courses.
$ratingquery = provider::get_sql_join('r', 'core_course', 'course', 'c.id', $u1->id);
$sql = "SELECT c.id FROM {course} c {$ratingquery->join} WHERE {$ratingquery->userwhere}";
$courses = $DB->get_records_sql($sql, $ratingquery->params);
$this->assertCount(3, $courses);
$this->assertTrue(isset($courses[$course1->id]));
$this->assertTrue(isset($courses[$course2->id]));
$this->assertTrue(isset($courses[$course3->id]));
// User u1 rated files in course 3 only.
$ratingquery = provider::get_sql_join('r', 'core_course', 'files', 'c.id', $u1->id);
$sql = "SELECT c.id FROM {course} c {$ratingquery->join} WHERE {$ratingquery->userwhere}";
$courses = $DB->get_records_sql($sql, $ratingquery->params);
$this->assertCount(1, $courses);
$this->assertFalse(isset($courses[$course1->id]));
$this->assertFalse(isset($courses[$course2->id]));
$this->assertTrue(isset($courses[$course3->id]));
// Return any course which the u2 has rated.
// User u2 rated only course 2.
$ratingquery = provider::get_sql_join('r', 'core_course', 'course', 'c.id', $u2->id);
$sql = "SELECT c.id FROM {course} c {$ratingquery->join} WHERE {$ratingquery->userwhere}";
$courses = $DB->get_records_sql($sql, $ratingquery->params);
$this->assertCount(1, $courses);
$this->assertFalse(isset($courses[$course1->id]));
$this->assertTrue(isset($courses[$course2->id]));
$this->assertFalse(isset($courses[$course3->id]));
// User u2 rated u3.
$ratingquery = provider::get_sql_join('r', 'user', 'user', 'u.id', $u2->id);
$sql = "SELECT u.id FROM {user} u {$ratingquery->join} WHERE {$ratingquery->userwhere}";
$users = $DB->get_records_sql($sql, $ratingquery->params);
$this->assertCount(1, $users);
$this->assertFalse(isset($users[$u1->id]));
$this->assertFalse(isset($users[$u2->id]));
$this->assertTrue(isset($users[$u3->id]));
// Return any course which the u3 has rated.
// User u3 did not rate anything.
$ratingquery = provider::get_sql_join('r', 'core_course', 'course', 'c.id', $u3->id);
$sql = "SELECT c.id FROM {course} c {$ratingquery->join} WHERE {$ratingquery->userwhere}";
$courses = $DB->get_records_sql($sql, $ratingquery->params);
$this->assertCount(0, $courses);
$this->assertFalse(isset($courses[$course1->id]));
$this->assertFalse(isset($courses[$course2->id]));
$this->assertFalse(isset($courses[$course3->id]));
}
/**
* Ensure that the get_sql_join function returns valid SQL which returns the correct list of rated itemids.
* This makes use of the optional inner join argument.
*/
public function test_get_sql_join_inner(): void {
global $DB;
$this->resetAfterTest();
$course1 = $this->getDataGenerator()->create_course();
$course2 = $this->getDataGenerator()->create_course();
$course3 = $this->getDataGenerator()->create_course();
$u1 = $this->getDataGenerator()->create_user();
$u2 = $this->getDataGenerator()->create_user();
$u3 = $this->getDataGenerator()->create_user();
// Rate the courses.
$rm = new \rating_manager();
$ratingoptions = (object) [
'component' => 'core_course',
'ratingarea' => 'course',
'scaleid' => 100,
];
// Rate all courses as u1, and something else in the same context.
$this->rate_as_user($u1->id, 'core_course', 'course', $course1->id, \context_course::instance($course1->id), 25);
$this->rate_as_user($u1->id, 'core_course', 'course', $course2->id, \context_course::instance($course2->id), 50);
$this->rate_as_user($u1->id, 'core_course', 'course', $course3->id, \context_course::instance($course3->id), 75);
$this->rate_as_user($u1->id, 'core_course', 'files', $course3->id, \context_course::instance($course3->id), 99);
// Rate course2 as u2, and something else in a different context/component..
$this->rate_as_user($u2->id, 'core_course', 'course', $course2->id, \context_course::instance($course2->id), 90);
$this->rate_as_user($u2->id, 'user', 'user', $u3->id, \context_user::instance($u3->id), 10);
// Return any course which the u1 has rated.
// u1 rated all three courses.
$ratingquery = provider::get_sql_join('r', 'core_course', 'course', 'c.id', $u1->id, true);
$sql = "SELECT c.id FROM {course} c {$ratingquery->join} WHERE {$ratingquery->userwhere}";
$courses = $DB->get_records_sql($sql, $ratingquery->params);
$this->assertCount(3, $courses);
$this->assertTrue(isset($courses[$course1->id]));
$this->assertTrue(isset($courses[$course2->id]));
$this->assertTrue(isset($courses[$course3->id]));
// User u1 rated files in course 3 only.
$ratingquery = provider::get_sql_join('r', 'core_course', 'files', 'c.id', $u1->id, true);
$sql = "SELECT c.id FROM {course} c {$ratingquery->join} WHERE {$ratingquery->userwhere}";
$courses = $DB->get_records_sql($sql, $ratingquery->params);
$this->assertCount(1, $courses);
$this->assertFalse(isset($courses[$course1->id]));
$this->assertFalse(isset($courses[$course2->id]));
$this->assertTrue(isset($courses[$course3->id]));
// Return any course which the u2 has rated.
// User u2 rated only course 2.
$ratingquery = provider::get_sql_join('r', 'core_course', 'course', 'c.id', $u2->id, true);
$sql = "SELECT c.id FROM {course} c {$ratingquery->join} WHERE {$ratingquery->userwhere}";
$courses = $DB->get_records_sql($sql, $ratingquery->params);
$this->assertCount(1, $courses);
$this->assertFalse(isset($courses[$course1->id]));
$this->assertTrue(isset($courses[$course2->id]));
$this->assertFalse(isset($courses[$course3->id]));
// User u2 rated u3.
$ratingquery = provider::get_sql_join('r', 'user', 'user', 'u.id', $u2->id, true);
$sql = "SELECT u.id FROM {user} u {$ratingquery->join} WHERE {$ratingquery->userwhere}";
$users = $DB->get_records_sql($sql, $ratingquery->params);
$this->assertCount(1, $users);
$this->assertFalse(isset($users[$u1->id]));
$this->assertFalse(isset($users[$u2->id]));
$this->assertTrue(isset($users[$u3->id]));
// Return any course which the u3 has rated.
// User u3 did not rate anything.
$ratingquery = provider::get_sql_join('r', 'core_course', 'course', 'c.id', $u3->id, true);
$sql = "SELECT c.id FROM {course} c {$ratingquery->join} WHERE {$ratingquery->userwhere}";
$courses = $DB->get_records_sql($sql, $ratingquery->params);
$this->assertCount(0, $courses);
$this->assertFalse(isset($courses[$course1->id]));
$this->assertFalse(isset($courses[$course2->id]));
$this->assertFalse(isset($courses[$course3->id]));
}
/**
* Ensure that export_area_ratings exports all ratings that a user has made, and all ratings for a users own content.
*/
public function test_export_area_ratings(): void {
global $DB;
$this->resetAfterTest();
$course1 = $this->getDataGenerator()->create_course();
$course2 = $this->getDataGenerator()->create_course();
$course3 = $this->getDataGenerator()->create_course();
$u1 = $this->getDataGenerator()->create_user();
$u2 = $this->getDataGenerator()->create_user();
$u3 = $this->getDataGenerator()->create_user();
// Rate the courses.
$rm = new \rating_manager();
$ratingoptions = (object) [
'component' => 'core_course',
'ratingarea' => 'course',
'scaleid' => 100,
];
// Rate all courses as u1, and something else in the same context.
$this->rate_as_user($u1->id, 'core_course', 'course', $course1->id, \context_course::instance($course1->id), 25);
$this->rate_as_user($u1->id, 'core_course', 'course', $course2->id, \context_course::instance($course2->id), 50);
$this->rate_as_user($u1->id, 'core_course', 'course', $course3->id, \context_course::instance($course3->id), 75);
$this->rate_as_user($u1->id, 'core_course', 'files', $course3->id, \context_course::instance($course3->id), 99);
$this->rate_as_user($u1->id, 'user', 'user', $u3->id, \context_user::instance($u3->id), 10);
// Rate course2 as u2, and something else in a different context/component..
$this->rate_as_user($u2->id, 'core_course', 'course', $course2->id, \context_course::instance($course2->id), 90);
$this->rate_as_user($u2->id, 'user', 'user', $u3->id, \context_user::instance($u3->id), 20);
// Test exports.
// User 1 rated all three courses, and the core_course, and user 3.
// User 1::course1 is stored in [] subcontext.
$context = \context_course::instance($course1->id);
$subcontext = [];
provider::export_area_ratings($u1->id, $context, $subcontext, 'core_course', 'course', $course1->id, true);
/** @var \core_privacy\tests\request\content_writer $writer */
$writer = writer::with_context($context);
$this->assertTrue($writer->has_any_data());
$rating = $writer->get_related_data($subcontext, 'rating');
$this->assert_has_rating($u1, 25, $rating);
// User 1::course2 is stored in ['foo'] subcontext.
$context = \context_course::instance($course2->id);
$subcontext = ['foo'];
provider::export_area_ratings($u1->id, $context, $subcontext, 'core_course', 'course', $course2->id, true);
/** @var \core_privacy\tests\request\content_writer $writer */
$writer = writer::with_context($context);
$this->assertTrue($writer->has_any_data());
$result = $writer->get_related_data($subcontext, 'rating');
$this->assertCount(1, $result);
$this->assert_has_rating($u1, 50, $result);
// User 1::course3 is stored in ['foo'] subcontext.
$context = \context_course::instance($course3->id);
$subcontext = ['foo'];
provider::export_area_ratings($u1->id, $context, $subcontext, 'core_course', 'course', $course3->id, true);
/** @var \core_privacy\tests\request\content_writer $writer */
$writer = writer::with_context($context);
$this->assertTrue($writer->has_any_data());
$result = $writer->get_related_data($subcontext, 'rating');
$this->assertCount(1, $result);
$this->assert_has_rating($u1, 75, $result);
// User 1::course3::files is stored in ['foo', 'files'] subcontext.
$context = \context_course::instance($course3->id);
$subcontext = ['foo', 'files'];
provider::export_area_ratings($u1->id, $context, $subcontext, 'core_course', 'files', $course3->id, true);
/** @var \core_privacy\tests\request\content_writer $writer */
$writer = writer::with_context($context);
$this->assertTrue($writer->has_any_data());
$result = $writer->get_related_data($subcontext, 'rating');
$this->assertCount(1, $result);
$this->assert_has_rating($u1, 99, $result);
// Both users 1 and 2 rated user 3.
// Exporting the data for user 3 should include both of those ratings.
$context = \context_user::instance($u3->id);
$subcontext = ['user'];
provider::export_area_ratings($u3->id, $context, $subcontext, 'user', 'user', $u3->id, false);
/** @var \core_privacy\tests\request\content_writer $writer */
$writer = writer::with_context($context);
$this->assertTrue($writer->has_any_data());
$result = $writer->get_related_data($subcontext, 'rating');
$this->assertCount(2, $result);
$this->assert_has_rating($u1, 10, $result);
$this->assert_has_rating($u2, 20, $result);
}
/**
* Test delete_ratings() method.
*/
public function test_delete_ratings(): void {
global $DB;
$this->resetAfterTest();
$course1 = $this->getDataGenerator()->create_course();
$course2 = $this->getDataGenerator()->create_course();
$course3 = $this->getDataGenerator()->create_course();
$u1 = $this->getDataGenerator()->create_user();
$u2 = $this->getDataGenerator()->create_user();
$u3 = $this->getDataGenerator()->create_user();
// Rate all courses as u1, and something else in the same context.
$this->rate_as_user($u1->id, 'core_course', 'course', $course1->id, \context_course::instance($course1->id), 25);
$this->rate_as_user($u1->id, 'core_course', 'course', $course2->id, \context_course::instance($course2->id), 50);
$this->rate_as_user($u1->id, 'core_course', 'course', $course3->id, \context_course::instance($course3->id), 75);
$this->rate_as_user($u1->id, 'core_course', 'files', $course3->id, \context_course::instance($course3->id), 99);
$this->rate_as_user($u1->id, 'core_user', 'user', $u3->id, \context_user::instance($u3->id), 10);
// Rate course2 as u2, and something else in a different context/component..
$this->rate_as_user($u2->id, 'core_course', 'course', $course2->id, \context_course::instance($course2->id), 90);
$this->rate_as_user($u2->id, 'core_user', 'user', $u3->id, \context_user::instance($u3->id), 20);
// Delete all ratings in course1.
$expectedratingscount = $DB->count_records('rating');
provider::delete_ratings(\context_course::instance($course1->id));
$expectedratingscount -= 1;
$this->assertEquals($expectedratingscount, $DB->count_records('rating'));
// Delete ratings in course2 specifying wrong component.
provider::delete_ratings(\context_course::instance($course2->id), 'other_component');
$this->assertEquals($expectedratingscount, $DB->count_records('rating'));
// Delete ratings in course2 specifying correct component.
provider::delete_ratings(\context_course::instance($course2->id), 'core_course');
$expectedratingscount -= 2;
$this->assertEquals($expectedratingscount, $DB->count_records('rating'));
// Delete user ratings specifyng all attributes.
provider::delete_ratings(\context_user::instance($u3->id), 'core_user', 'user', $u3->id);
$expectedratingscount -= 2;
$this->assertEquals($expectedratingscount, $DB->count_records('rating'));
}
/**
* Test delete_ratings_select() method.
*/
public function test_delete_ratings_select(): void {
global $DB;
$this->resetAfterTest();
$course1 = $this->getDataGenerator()->create_course();
$course2 = $this->getDataGenerator()->create_course();
$course3 = $this->getDataGenerator()->create_course();
$u1 = $this->getDataGenerator()->create_user();
$u2 = $this->getDataGenerator()->create_user();
$u3 = $this->getDataGenerator()->create_user();
// Rate all courses as u1, and something else in the same context.
$this->rate_as_user($u1->id, 'core_course', 'course', $course1->id, \context_course::instance($course1->id), 25);
$this->rate_as_user($u1->id, 'core_course', 'course', $course2->id, \context_course::instance($course2->id), 50);
$this->rate_as_user($u1->id, 'core_course', 'course', $course3->id, \context_course::instance($course3->id), 75);
$this->rate_as_user($u1->id, 'core_course', 'files', $course3->id, \context_course::instance($course3->id), 99);
$this->rate_as_user($u1->id, 'core_user', 'user', $u3->id, \context_user::instance($u3->id), 10);
// Rate course2 as u2, and something else in a different context/component..
$this->rate_as_user($u2->id, 'core_course', 'course', $course2->id, \context_course::instance($course2->id), 90);
$this->rate_as_user($u2->id, 'core_user', 'user', $u3->id, \context_user::instance($u3->id), 20);
// Delete ratings in course1.
list($sql, $params) = $DB->get_in_or_equal([$course1->id, $course2->id], SQL_PARAMS_NAMED);
$expectedratingscount = $DB->count_records('rating');
provider::delete_ratings_select(\context_course::instance($course1->id),
'core_course', 'course', $sql, $params);
$expectedratingscount -= 1;
$this->assertEquals($expectedratingscount, $DB->count_records('rating'));
}
/**
* Assert that a user has the correct rating.
*
* @param \stdClass $author The user with the rating
* @param int $score The rating that was given
* @param \stdClass[] The ratings which were found
*/
protected function assert_has_rating($author, $score, $actual) {
$found = false;
foreach ($actual as $rating) {
if ($author->id == $rating->author) {
$found = true;
$this->assertEquals($score, $rating->rating);
}
}
$this->assertTrue($found);
}
}
+385
View File
@@ -0,0 +1,385 @@
<?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_rating;
use rating_manager;
defined('MOODLE_INTERNAL') || die();
// Include all the needed stuff.
global $CFG;
require_once($CFG->dirroot . '/rating/lib.php');
/**
* Unit test case for all the rating/lib.php requiring DB mockup & manipulation
*
* @package core_rating
* @category test
* @copyright 2011 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @covers \rating
*/
class rating_test extends \advanced_testcase {
protected $syscontext;
protected $neededcaps = array('view', 'viewall', 'viewany', 'rate');
protected $originaldefaultfrontpageroleid;
public function setUp(): void {
global $CFG;
parent::setUp();
$this->resetAfterTest(true);
$CFG->defaultfrontpageroleid = null;
}
/**
* Test the current get_ratings method main sql
*/
public function test_get_ratings_sql(): void {
global $DB;
// We load 3 items. Each is rated twice. For simplicity itemid == user id of the item owner.
$ctxid = \context_system::instance()->id;
$ratings = array(
// User 1's items. Average == 2.
array('contextid' => $ctxid,
'component' => 'mod_forum',
'ratingarea' => 'post',
'itemid' => 1,
'scaleid' => 10,
'rating' => 1,
'userid' => 2,
'timecreated' => 1,
'timemodified' => 1),
array('contextid' => $ctxid,
'component' => 'mod_forum',
'ratingarea' => 'post',
'itemid' => 1,
'scaleid' => 10,
'rating' => 3,
'userid' => 3,
'timecreated' => 1,
'timemodified' => 1),
// User 2's items. Average == 3.
array('contextid' => $ctxid,
'component' => 'mod_forum',
'ratingarea' => 'post',
'itemid' => 2,
'scaleid' => 10,
'rating' => 1,
'userid' => 1,
'timecreated' => 1,
'timemodified' => 1),
array('contextid' => $ctxid,
'component' => 'mod_forum',
'ratingarea' => 'post',
'itemid' => 2,
'scaleid' => 10,
'rating' => 4,
'userid' => 3,
'timecreated' => 1,
'timemodified' => 1),
// User 3's items. Average == 4.
array('contextid' => $ctxid,
'component' => 'mod_forum',
'ratingarea' => 'post',
'itemid' => 3,
'scaleid' => 10,
'rating' => 3,
'userid' => 1,
'timecreated' => 1,
'timemodified' => 1),
array('contextid' => $ctxid,
'component' => 'mod_forum',
'ratingarea' => 'post',
'itemid' => 3,
'scaleid' => 10,
'rating' => 5,
'userid' => 2,
'timecreated' => 1,
'timemodified' => 1)
);
foreach ($ratings as $rating) {
$DB->insert_record('rating', $rating);
}
// A post (item) by user 1 (rated above by user 2 and 3 with average = 2).
$user1posts = array(
(object)array('id' => 1, 'userid' => 1, 'message' => 'hello'));
// A post (item) by user 2 (rated above by user 1 and 3 with average = 3).
$user2posts = array(
(object)array('id' => 2, 'userid' => 2, 'message' => 'world'));
// A post (item) by user 3 (rated above by user 1 and 2 with average = 4).
$user3posts = array(
(object)array('id' => 3, 'userid' => 3, 'message' => 'moodle'));
// Prepare the default options.
$defaultoptions = array (
'context' => \context_system::instance(),
'component' => 'mod_forum',
'ratingarea' => 'post',
'scaleid' => 10,
'aggregate' => RATING_AGGREGATE_AVERAGE);
$rm = new mockup_rating_manager();
// STEP 1: Retreive ratings using the current user.
// Get results for user 1's item (expected average 1 + 3 / 2 = 2).
$toptions = (object)array_merge($defaultoptions, array('items' => $user1posts));
$result = $rm->get_ratings($toptions);
$this->assertEquals(count($result), count($user1posts));
$this->assertEquals($result[0]->id, $user1posts[0]->id);
$this->assertEquals($result[0]->userid, $user1posts[0]->userid);
$this->assertEquals($result[0]->message, $user1posts[0]->message);
$this->assertEquals($result[0]->rating->count, 2);
$this->assertEquals($result[0]->rating->aggregate, 2);
// Note that $result[0]->rating->rating is somewhat random.
// We didn't supply a user ID so $USER was used which will vary depending on who runs the tests.
// Get results for items of user 2 (expected average 1 + 4 / 2 = 2.5).
$toptions = (object)array_merge($defaultoptions, array('items' => $user2posts));
$result = $rm->get_ratings($toptions);
$this->assertEquals(count($result), count($user2posts));
$this->assertEquals($result[0]->id, $user2posts[0]->id);
$this->assertEquals($result[0]->userid, $user2posts[0]->userid);
$this->assertEquals($result[0]->message, $user2posts[0]->message);
$this->assertEquals($result[0]->rating->count, 2);
$this->assertEquals($result[0]->rating->aggregate, 2.5);
// Note that $result[0]->rating->rating is somewhat random.
// We didn't supply a user ID so $USER was used which will vary depending on who runs the tests.
// Get results for items of user 3 (expected average 3 + 5 / 2 = 4).
$toptions = (object)array_merge($defaultoptions, array('items' => $user3posts));
$result = $rm->get_ratings($toptions);
$this->assertEquals(count($result), count($user3posts));
$this->assertEquals($result[0]->id, $user3posts[0]->id);
$this->assertEquals($result[0]->userid, $user3posts[0]->userid);
$this->assertEquals($result[0]->message, $user3posts[0]->message);
$this->assertEquals($result[0]->rating->count, 2);
$this->assertEquals($result[0]->rating->aggregate, 4);
// Note that $result[0]->rating->rating is somewhat random.
// We didn't supply a user ID so $USER was used which will vary depending on who runs the tests.
// Get results for items of user 1 & 2 together (expected averages are 2 and 2.5, as tested above).
$posts = array_merge($user1posts, $user2posts);
$toptions = (object)array_merge($defaultoptions, array('items' => $posts));
$result = $rm->get_ratings($toptions);
$this->assertEquals(count($result), count($posts));
$this->assertEquals($result[0]->id, $posts[0]->id);
$this->assertEquals($result[0]->userid, $posts[0]->userid);
$this->assertEquals($result[0]->message, $posts[0]->message);
$this->assertEquals($result[0]->rating->count, 2);
$this->assertEquals($result[0]->rating->aggregate, 2);
// Note that $result[0]->rating->rating is somewhat random.
// We didn't supply a user ID so $USER was used which will vary depending on who runs the tests.
$this->assertEquals($result[1]->id, $posts[1]->id);
$this->assertEquals($result[1]->userid, $posts[1]->userid);
$this->assertEquals($result[1]->message, $posts[1]->message);
$this->assertEquals($result[1]->rating->count, 2);
$this->assertEquals($result[1]->rating->aggregate, 2.5);
// Note that $result[0]->rating->rating is somewhat random.
// We didn't supply a user ID so $USER was used which will vary depending on who runs the tests.
// STEP 2: Retrieve ratings by a specified user.
// We still expect complete aggregations and counts.
// Get results for items of user 1 rated by user 2 (avg 2, rating 1).
$toptions = (object)array_merge($defaultoptions, array('items' => $user1posts, 'userid' => 2));
$result = $rm->get_ratings($toptions);
$this->assertEquals(count($result), count($user1posts));
$this->assertEquals($result[0]->id, $user1posts[0]->id);
$this->assertEquals($result[0]->userid, $user1posts[0]->userid);
$this->assertEquals($result[0]->message, $user1posts[0]->message);
$this->assertEquals($result[0]->rating->count, 2);
$this->assertEquals($result[0]->rating->aggregate, 2);
$this->assertEquals($result[0]->rating->rating, 1); // User 2 rated user 1 "1".
$this->assertEquals($result[0]->rating->userid, $toptions->userid); // Must be the passed userid.
// Get results for items of user 1 rated by user 3.
$toptions = (object)array_merge($defaultoptions, array('items' => $user1posts, 'userid' => 3));
$result = $rm->get_ratings($toptions);
$this->assertEquals(count($result), count($user1posts));
$this->assertEquals($result[0]->id, $user1posts[0]->id);
$this->assertEquals($result[0]->userid, $user1posts[0]->userid);
$this->assertEquals($result[0]->message, $user1posts[0]->message);
$this->assertEquals($result[0]->rating->count, 2);
$this->assertEquals($result[0]->rating->aggregate, 2);
$this->assertEquals($result[0]->rating->rating, 3); // User 3 rated user 1 "3".
$this->assertEquals($result[0]->rating->userid, $toptions->userid); // Must be the passed userid.
// Get results for items of user 1 & 2 together rated by user 3.
$posts = array_merge($user1posts, $user2posts);
$toptions = (object)array_merge($defaultoptions, array('items' => $posts, 'userid' => 3));
$result = $rm->get_ratings($toptions);
$this->assertEquals(count($result), count($posts));
$this->assertEquals($result[0]->id, $posts[0]->id);
$this->assertEquals($result[0]->userid, $posts[0]->userid);
$this->assertEquals($result[0]->message, $posts[0]->message);
$this->assertEquals($result[0]->rating->count, 2);
$this->assertEquals($result[0]->rating->aggregate, 2);
$this->assertEquals($result[0]->rating->rating, 3); // User 3 rated user 1 "3".
$this->assertEquals($result[0]->rating->userid, $toptions->userid); // Must be the passed userid.
$this->assertEquals($result[1]->id, $posts[1]->id);
$this->assertEquals($result[1]->userid, $posts[1]->userid);
$this->assertEquals($result[1]->message, $posts[1]->message);
$this->assertEquals($result[1]->rating->count, 2);
$this->assertEquals($result[1]->rating->aggregate, 2.5);
$this->assertEquals($result[0]->rating->rating, 3); // User 3 rated user 2 "5".
$this->assertEquals($result[1]->rating->userid, $toptions->userid); // Must be the passed userid.
// STEP 3: Some special cases.
// Get results for user 1's items (expected average 1 + 3 / 2 = 2).
// Supplying a non-existent user id so no rating from that user should be found.
$toptions = (object)array_merge($defaultoptions, array('items' => $user1posts));
$toptions->userid = 123456; // Non-existent user.
$result = $rm->get_ratings($toptions);
$this->assertNull($result[0]->rating->userid);
$this->assertNull($result[0]->rating->rating);
$this->assertEquals($result[0]->rating->aggregate, 2); // Should still get the aggregate.
// Get results for items of user 2 (expected average 1 + 4 / 2 = 2.5).
// Supplying the user id of the user who owns the items so no rating should be found.
$toptions = (object)array_merge($defaultoptions, array('items' => $user2posts));
$toptions->userid = 2; // User 2 viewing the ratings of their own item.
$result = $rm->get_ratings($toptions);
// These should be null as the user is viewing their own item and thus cannot rate.
$this->assertNull($result[0]->rating->userid);
$this->assertNull($result[0]->rating->rating);
$this->assertEquals($result[0]->rating->aggregate, 2.5); // Should still get the aggregate.
}
/**
* Data provider for get_aggregate_string tests.
*
* @return array
*/
public function get_aggregate_string_provider() {
return [
'Non-numeric aggregate produces empty string' => [
RATING_AGGREGATE_NONE,
'string',
null,
['Foo', 'Bar'],
'',
],
'Aggregate count produces empty string' => [
RATING_AGGREGATE_COUNT,
0,
null,
['Foo', 'Bar'],
'',
],
'Numeric SUM with non-numeric scale produces returns original value' => [
RATING_AGGREGATE_SUM,
10,
false,
['Foo', 'Bar'],
'10',
],
'Numeric SUM with non-numeric scale produces returns rounded value' => [
RATING_AGGREGATE_SUM,
10.45,
false,
['Foo', 'Bar'],
'10.5',
],
'Numeric SUM with numeric scale produces returns rounded value' => [
RATING_AGGREGATE_SUM,
10.45,
true,
['Foo', 'Bar'],
'10.5',
],
'Numeric AVERAGE with numeric scale produces returns rounded value' => [
RATING_AGGREGATE_AVERAGE,
10.45,
true,
['Foo', 'Bar'],
'10.5',
],
'Numeric AVERAGE with non-numeric scale produces returns indexed value (0)' => [
RATING_AGGREGATE_AVERAGE,
0,
false,
['Foo', 'Bar'],
'Foo',
],
'Numeric AVERAGE with non-numeric scale produces returns indexed value (1)' => [
RATING_AGGREGATE_AVERAGE,
1,
false,
['Foo', 'Bar'],
'Bar',
],
];
}
/**
* Test the value returned by get_aggregate_string().
*
* @dataProvider get_aggregate_string_provider
*/
public function test_get_aggregate_string($method, $aggregate, $isnumeric, $scaleitems, $expectation): void {
$options = new \stdClass();
$options->aggregate = $aggregate;
$options->context = null;
$options->component = null;
$options->ratingarea = null;
$options->itemid = null;
$options->scaleid = null;
$options->userid = null;
$options->settings = new \stdClass();
$options->settings->aggregationmethod = $method;
$options->settings->scale = new \stdClass();
$options->settings->scale->isnumeric = $isnumeric;
$options->settings->scale->scaleitems = $scaleitems;
$rating = new \rating($options);
$this->assertEquals($expectation, $rating->get_aggregate_string());
}
}
/**
* rating_manager subclass for unit testing without requiring capabilities to be loaded
*/
class mockup_rating_manager extends rating_manager {
/**
* Overwrite get_plugin_permissions_array() so it always return granted perms for unit testing
*/
public function get_plugin_permissions_array($contextid, $component, $ratingarea) {
return array(
'rate' => true,
'view' => true,
'viewany' => true,
'viewall' => true);
}
}