MDL-65313 core_favourite: add component-scoped favourite service class
[moodle.git] / favourites / tests / user_favourite_service_test.php
CommitLineData
77105132
JD
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Testing the service layer within core_favourites.
19 *
20 * @package core_favourites
21 * @category test
22 * @copyright 2018 Jake Dallimore <jrhdallimore@gmail.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
cfaf86b0 25use \core_favourites\local\entity\favourite;
77105132
JD
26defined('MOODLE_INTERNAL') || die();
27
28/**
0551ed35 29 * Test class covering the user_favourite_service within the service layer of favourites.
77105132
JD
30 *
31 * @copyright 2018 Jake Dallimore <jrhdallimore@gmail.com>
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 */
0551ed35 34class user_favourite_service_testcase extends advanced_testcase {
77105132
JD
35
36 public function setUp() {
37 $this->resetAfterTest();
38 }
39
40 // Basic setup stuff to be reused in most tests.
41 protected function setup_users_and_courses() {
42 $user1 = self::getDataGenerator()->create_user();
43 $user1context = \context_user::instance($user1->id);
44 $user2 = self::getDataGenerator()->create_user();
45 $user2context = \context_user::instance($user2->id);
46 $course1 = self::getDataGenerator()->create_course();
47 $course2 = self::getDataGenerator()->create_course();
48 $course1context = context_course::instance($course1->id);
49 $course2context = context_course::instance($course2->id);
50 return [$user1context, $user2context, $course1context, $course2context];
51 }
52
53 /**
54 * Generates an in-memory repository for testing, using an array store for CRUD stuff.
55 *
56 * @param array $mockstore
57 * @return \PHPUnit\Framework\MockObject\MockObject
58 */
59 protected function get_mock_repository(array $mockstore) {
60 // This mock will just store data in an array.
b7a3ec6f 61 $mockrepo = $this->getMockBuilder(\core_favourites\local\repository\favourite_repository_interface::class)
77105132
JD
62 ->setMethods([])
63 ->getMock();
64 $mockrepo->expects($this->any())
65 ->method('add')
cfaf86b0 66 ->will($this->returnCallback(function(favourite $favourite) use (&$mockstore) {
77105132
JD
67 // Mock implementation of repository->add(), where an array is used instead of the DB.
68 // Duplicates are confirmed via the unique key, and exceptions thrown just like a real repo.
69 $key = $favourite->userid . $favourite->component . $favourite->itemtype . $favourite->itemid
70 . $favourite->contextid;
71
72 // Check the objects for the unique key.
73 foreach ($mockstore as $item) {
74 if ($item->uniquekey == $key) {
75 throw new \moodle_exception('Favourite already exists');
76 }
77 }
78 $index = count($mockstore); // Integer index.
79 $favourite->uniquekey = $key; // Simulate the unique key constraint.
80 $favourite->id = $index;
81 $mockstore[$index] = $favourite;
82 return $mockstore[$index];
83 })
84 );
85 $mockrepo->expects($this->any())
86 ->method('find_by')
8ffbe9c1 87 ->will($this->returnCallback(function(array $criteria, int $limitfrom = 0, int $limitnum = 0) use (&$mockstore) {
77105132
JD
88 // Check the mockstore for all objects with properties matching the key => val pairs in $criteria.
89 foreach ($mockstore as $index => $mockrow) {
90 $mockrowarr = (array)$mockrow;
91 if (array_diff($criteria, $mockrowarr) == []) {
92 $returns[$index] = $mockrow;
93 }
94 }
8ffbe9c1
JD
95 // Return a subset of the records, according to the paging options, if set.
96 if ($limitnum != 0) {
97 return array_slice($returns, $limitfrom, $limitnum);
98 }
99 // Otherwise, just return the full set.
77105132
JD
100 return $returns;
101 })
102 );
103 $mockrepo->expects($this->any())
104 ->method('find_favourite')
105 ->will($this->returnCallback(function(int $userid, string $comp, string $type, int $id, int $ctxid) use (&$mockstore) {
106 // Check the mockstore for all objects with properties matching the key => val pairs in $criteria.
107 $crit = ['userid' => $userid, 'component' => $comp, 'itemtype' => $type, 'itemid' => $id, 'contextid' => $ctxid];
108 foreach ($mockstore as $fakerow) {
109 $fakerowarr = (array)$fakerow;
110 if (array_diff($crit, $fakerowarr) == []) {
111 return $fakerow;
112 }
113 }
9e189a91 114 throw new \dml_missing_record_exception("Item not found");
77105132
JD
115 })
116 );
117 $mockrepo->expects($this->any())
118 ->method('find')
119 ->will($this->returnCallback(function(int $id) use (&$mockstore) {
120 return $mockstore[$id];
121 })
122 );
123 $mockrepo->expects($this->any())
124 ->method('exists')
125 ->will($this->returnCallback(function(int $id) use (&$mockstore) {
126 return array_key_exists($id, $mockstore);
127 })
128 );
b81722e2 129 $mockrepo->expects($this->any())
9e189a91 130 ->method('count_by')
b81722e2 131 ->will($this->returnCallback(function(array $criteria) use (&$mockstore) {
9e189a91 132 $count = 0;
b81722e2
JD
133 // Check the mockstore for all objects with properties matching the key => val pairs in $criteria.
134 foreach ($mockstore as $index => $mockrow) {
135 $mockrowarr = (array)$mockrow;
136 if (array_diff($criteria, $mockrowarr) == []) {
9e189a91 137 $count++;
b81722e2
JD
138 }
139 }
9e189a91 140 return $count;
b81722e2
JD
141 })
142 );
77105132
JD
143 $mockrepo->expects($this->any())
144 ->method('delete')
145 ->will($this->returnCallback(function(int $id) use (&$mockstore) {
146 foreach ($mockstore as $mockrow) {
147 if ($mockrow->id == $id) {
148 unset($mockstore[$id]);
149 }
150 }
151 })
152 );
9e189a91
RW
153 $mockrepo->expects($this->any())
154 ->method('exists_by')
155 ->will($this->returnCallback(function(array $criteria) use (&$mockstore) {
156 // Check the mockstore for all objects with properties matching the key => val pairs in $criteria.
157 foreach ($mockstore as $index => $mockrow) {
158 $mockrowarr = (array)$mockrow;
159 if (array_diff($criteria, $mockrowarr) == []) {
160 return true;
161 }
162 }
163 return false;
164 })
165 );
77105132
JD
166 return $mockrepo;
167 }
168
169 /**
0551ed35 170 * Test getting a user_favourite_service from the static locator.
77105132
JD
171 */
172 public function test_get_service_for_user_context() {
173 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
0551ed35
JD
174 $userservice = \core_favourites\service_factory::get_service_for_user_context($user1context);
175 $this->assertInstanceOf(\core_favourites\local\service\user_favourite_service::class, $userservice);
77105132
JD
176 }
177
178 /**
179 * Test confirming an item can be favourited only once.
180 */
181 public function test_create_favourite_basic() {
182 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
183
0551ed35 184 // Get a user_favourite_service for a user.
77105132 185 $repo = $this->get_mock_repository([]); // Mock repository, using the array as a mock DB.
0551ed35 186 $user1service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
77105132
JD
187
188 // Favourite a course.
189 $favourite1 = $user1service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
190 $this->assertObjectHasAttribute('id', $favourite1);
191
192 // Try to favourite the same course again.
193 $this->expectException('moodle_exception');
194 $user1service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
195 }
196
197 /**
198 * Test confirming that an exception is thrown if trying to favourite an item for a non-existent component.
199 */
200 public function test_create_favourite_nonexistent_component() {
201 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
202
0551ed35 203 // Get a user_favourite_service for the user.
77105132 204 $repo = $this->get_mock_repository([]); // Mock repository, using the array as a mock DB.
0551ed35 205 $user1service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
77105132
JD
206
207 // Try to favourite something in a non-existent component.
208 $this->expectException('moodle_exception');
209 $user1service->create_favourite('core_cccourse', 'my_area', $course1context->instanceid, $course1context);
210 }
211
212 /**
213 * Test fetching favourites for single user, by area.
214 */
215 public function test_find_favourites_by_type_single_user() {
216 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
217
0551ed35 218 // Get a user_favourite_service for the user.
77105132 219 $repo = $this->get_mock_repository([]); // Mock repository, using the array as a mock DB.
0551ed35 220 $service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
77105132
JD
221
222 // Favourite 2 courses, in separate areas.
223 $fav1 = $service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
224 $fav2 = $service->create_favourite('core_course', 'anothertype', $course2context->instanceid, $course2context);
225
226 // Verify we can get favourites by area.
227 $favourites = $service->find_favourites_by_type('core_course', 'course');
228 $this->assertInternalType('array', $favourites);
229 $this->assertCount(1, $favourites); // We only get favourites for the 'core_course/course' area.
230 $this->assertAttributeEquals($fav1->id, 'id', $favourites[$fav1->id]);
231
232 $favourites = $service->find_favourites_by_type('core_course', 'anothertype');
233 $this->assertInternalType('array', $favourites);
234 $this->assertCount(1, $favourites); // We only get favourites for the 'core_course/course' area.
235 $this->assertAttributeEquals($fav2->id, 'id', $favourites[$fav2->id]);
236 }
237
238 /**
239 * Make sure the find_favourites_by_type() method only returns favourites for the scoped user.
240 */
241 public function test_find_favourites_by_type_multiple_users() {
242 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
243
0551ed35 244 // Get a user_favourite_service for 2 users.
77105132 245 $repo = $this->get_mock_repository([]);
0551ed35
JD
246 $user1service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
247 $user2service = new \core_favourites\local\service\user_favourite_service($user2context, $repo);
77105132
JD
248
249 // Now, as each user, favourite the same course.
250 $fav1 = $user1service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
251 $fav2 = $user2service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
252
253 // Verify find_favourites_by_type only returns results for the user to which the service is scoped.
254 $user1favourites = $user1service->find_favourites_by_type('core_course', 'course');
255 $this->assertInternalType('array', $user1favourites);
256 $this->assertCount(1, $user1favourites); // We only get favourites for the 'core_course/course' area for $user1.
257 $this->assertAttributeEquals($fav1->id, 'id', $user1favourites[$fav1->id]);
258
259 $user2favourites = $user2service->find_favourites_by_type('core_course', 'course');
260 $this->assertInternalType('array', $user2favourites);
261 $this->assertCount(1, $user2favourites); // We only get favourites for the 'core_course/course' area for $user2.
262 $this->assertAttributeEquals($fav2->id, 'id', $user2favourites[$fav2->id]);
263 }
264
265 /**
266 * Test confirming that an exception is thrown if trying to get favourites for a non-existent component.
267 */
268 public function test_find_favourites_by_type_nonexistent_component() {
269 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
270
0551ed35 271 // Get a user_favourite_service for the user.
77105132 272 $repo = $this->get_mock_repository([]);
0551ed35 273 $service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
77105132
JD
274
275 // Verify we get an exception if we try to search for favourites in an invalid component.
276 $this->expectException('moodle_exception');
277 $service->find_favourites_by_type('cccore_notreal', 'something');
278 }
279
8ffbe9c1
JD
280 /**
281 * Test confirming the pagination support for the find_favourites_by_type() method.
282 */
283 public function test_find_favourites_by_type_pagination() {
284 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
285
0551ed35 286 // Get a user_favourite_service for the user.
8ffbe9c1 287 $repo = $this->get_mock_repository([]);
0551ed35 288 $service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
8ffbe9c1
JD
289
290 // Favourite 10 arbitrary items.
291 foreach (range(1, 10) as $i) {
292 $service->create_favourite('core_course', 'course', $i, $course1context);
293 }
294
295 // Verify we have 10 favourites.
296 $this->assertCount(10, $service->find_favourites_by_type('core_course', 'course'));
297
298 // Verify we get back 5 favourites for page 1.
299 $favourites = $service->find_favourites_by_type('core_course', 'course', 0, 5);
300 $this->assertCount(5, $favourites);
301
302 // Verify we get back 5 favourites for page 2.
303 $favourites = $service->find_favourites_by_type('core_course', 'course', 5, 5);
304 $this->assertCount(5, $favourites);
305
306 // Verify we get back an empty array if querying page 3.
307 $favourites = $service->find_favourites_by_type('core_course', 'course', 10, 5);
308 $this->assertCount(0, $favourites);
309 }
310
77105132
JD
311 /**
312 * Test confirming the basic deletion behaviour.
313 */
314 public function test_delete_favourite_basic() {
315 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
316
0551ed35 317 // Get a user_favourite_service for the user.
77105132 318 $repo = $this->get_mock_repository([]);
0551ed35 319 $service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
77105132
JD
320
321 // Favourite a course.
322 $fav1 = $service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
323 $this->assertTrue($repo->exists($fav1->id));
324
325 // Delete the favourite.
326 $service->delete_favourite('core_course', 'course', $course1context->instanceid, $course1context);
327
328 // Verify the favourite doesn't exist.
329 $this->assertFalse($repo->exists($fav1->id));
330
331 // Try to delete a favourite which we know doesn't exist.
332 $this->expectException(\moodle_exception::class);
333 $service->delete_favourite('core_course', 'course', $course1context->instanceid, $course1context);
334 }
b81722e2
JD
335
336 /**
337 * Test confirming the behaviour of the favourite_exists() method.
338 */
339 public function test_favourite_exists() {
340 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
341
342 // Get a user_favourite_service for the user.
343 $repo = $this->get_mock_repository([]);
344 $service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
345
346 // Favourite a course.
347 $fav1 = $service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
348
349 // Verify we can check existence of the favourite.
350 $this->assertTrue(
351 $service->favourite_exists(
352 'core_course',
353 'course',
354 $course1context->instanceid,
355 $course1context
356 )
357 );
358
359 // And one that we know doesn't exist.
360 $this->assertFalse(
361 $service->favourite_exists(
362 'core_course',
363 'someothertype',
364 $course1context->instanceid,
365 $course1context
366 )
367 );
368 }
9e189a91
RW
369
370 /**
371 * Test confirming the behaviour of the get_favourite() method.
372 */
373 public function test_get_favourite() {
374 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
375
376 // Get a user_favourite_service for the user.
377 $repo = $this->get_mock_repository([]);
378 $service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
379
380 // Favourite a course.
381 $fav1 = $service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
382
383 $result = $service->get_favourite(
384 'core_course',
385 'course',
386 $course1context->instanceid,
387 $course1context
388 );
389 // Verify we can get the favourite.
390 $this->assertEquals($fav1->id, $result->id);
391
392 // And one that we know doesn't exist.
393 $this->assertNull(
394 $service->get_favourite(
395 'core_course',
396 'someothertype',
397 $course1context->instanceid,
398 $course1context
399 )
400 );
401 }
402
403 /**
404 * Test confirming the behaviour of the count_favourites_by_type() method.
405 */
406 public function test_count_favourites_by_type() {
407 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
408
409 // Get a user_favourite_service for the user.
410 $repo = $this->get_mock_repository([]);
411 $service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
412
413 $this->assertEquals(0, $service->count_favourites_by_type('core_course', 'course', $course1context));
414 // Favourite a course.
415 $service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
416
417 $this->assertEquals(1, $service->count_favourites_by_type('core_course', 'course', $course1context));
418
419 // Favourite another course.
420 $service->create_favourite('core_course', 'course', $course2context->instanceid, $course1context);
421
422 $this->assertEquals(2, $service->count_favourites_by_type('core_course', 'course', $course1context));
423
424 // Favourite a course in another context.
425 $service->create_favourite('core_course', 'course', $course2context->instanceid, $course2context);
426
427 // Doesn't affect original context.
428 $this->assertEquals(2, $service->count_favourites_by_type('core_course', 'course', $course1context));
429 // Gets counted if we include all contexts.
430 $this->assertEquals(3, $service->count_favourites_by_type('core_course', 'course'));
431 }
92bea7db
JD
432
433 /**
434 * Verify that the join sql generated by get_join_sql_by_type is valid and can be used to include favourite information.
435 */
436 public function test_get_join_sql_by_type() {
437 global $DB;
438 list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
439
440 // Get a user_favourite_service for the user.
441 // We need to use a real (DB) repository, as we want to run the SQL.
442 $repo = new \core_favourites\local\repository\favourite_repository();
443 $service = new \core_favourites\local\service\user_favourite_service($user1context, $repo);
444
445 // Favourite the first course only.
446 $service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
447
448 // Generate the join snippet.
449 list($favsql, $favparams) = $service->get_join_sql_by_type('core_course', 'course', 'favalias', 'c.id');
450
451 // Join against a simple select, including the 2 courses only.
452 $params = ['courseid1' => $course1context->instanceid, 'courseid2' => $course2context->instanceid];
453 $params = $params + $favparams;
454 $records = $DB->get_records_sql("SELECT c.id, favalias.component
455 FROM {course} c $favsql
456 WHERE c.id = :courseid1 OR c.id = :courseid2", $params);
457
458 // Verify the favourite information is returned, but only for the favourited course.
459 $this->assertCount(2, $records);
460 $this->assertEquals('core_course', $records[$course1context->instanceid]->component);
461 $this->assertEmpty($records[$course2context->instanceid]->component);
462 }
77105132 463}