MDL-63658 core_favourites: adding paging support to the service layer
[moodle.git] / favourites / tests / service_test.php
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/>.
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  */
26 defined('MOODLE_INTERNAL') || die();
28 /**
29  * Test class covering the user_favourites_service within the service layer of favourites.
30  *
31  * @copyright  2018 Jake Dallimore <jrhdallimore@gmail.com>
32  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33  */
34 class user_favourites_service_testcase extends advanced_testcase {
36     public function setUp() {
37         $this->resetAfterTest();
38     }
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     }
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.
61         $mockrepo = $this->getMockBuilder(\core_favourites\local\repository\ifavourites_repository::class)
62             ->setMethods([])
63             ->getMock();
64         $mockrepo->expects($this->any())
65             ->method('add')
66             ->will($this->returnCallback(function(\stdclass $favourite) use (&$mockstore) {
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;
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')
87             ->will($this->returnCallback(function(array $criteria, int $limitfrom = 0, int $limitnum = 0) use (&$mockstore) {
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                 }
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.
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                 }
114                 throw new \moodle_exception("Item not found");
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         );
129         $mockrepo->expects($this->any())
130             ->method('delete')
131             ->will($this->returnCallback(function(int $id) use (&$mockstore) {
132                 foreach ($mockstore as $mockrow) {
133                     if ($mockrow->id == $id) {
134                         unset($mockstore[$id]);
135                     }
136                 }
137             })
138         );
139         return $mockrepo;
140     }
142     /**
143      * Test getting a user_favourites_service from the static locator.
144      */
145     public function test_get_service_for_user_context() {
146         list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
147         $userservice = \core_favourites\services::get_service_for_user_context($user1context);
148         $this->assertInstanceOf(\core_favourites\local\service\user_favourites_service::class, $userservice);
149     }
151     /**
152      * Test confirming an item can be favourited only once.
153      */
154     public function test_create_favourite_basic() {
155         list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
157         // Get a user_favourites_service for a user.
158         $repo = $this->get_mock_repository([]); // Mock repository, using the array as a mock DB.
159         $user1service = new \core_favourites\local\service\user_favourites_service($user1context, $repo);
161         // Favourite a course.
162         $favourite1 = $user1service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
163         $this->assertObjectHasAttribute('id', $favourite1);
165         // Try to favourite the same course again.
166         $this->expectException('moodle_exception');
167         $user1service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
168     }
170     /**
171      * Test confirming that an exception is thrown if trying to favourite an item for a non-existent component.
172      */
173     public function test_create_favourite_nonexistent_component() {
174         list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
176         // Get a user_favourites_service for the user.
177         $repo = $this->get_mock_repository([]); // Mock repository, using the array as a mock DB.
178         $user1service = new \core_favourites\local\service\user_favourites_service($user1context, $repo);
180         // Try to favourite something in a non-existent component.
181         $this->expectException('moodle_exception');
182         $user1service->create_favourite('core_cccourse', 'my_area', $course1context->instanceid, $course1context);
183     }
185     /**
186      * Test fetching favourites for single user, by area.
187      */
188     public function test_find_favourites_by_type_single_user() {
189         list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
191         // Get a user_favourites_service for the user.
192         $repo = $this->get_mock_repository([]); // Mock repository, using the array as a mock DB.
193         $service = new \core_favourites\local\service\user_favourites_service($user1context, $repo);
195         // Favourite 2 courses, in separate areas.
196         $fav1 = $service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
197         $fav2 = $service->create_favourite('core_course', 'anothertype', $course2context->instanceid, $course2context);
199         // Verify we can get favourites by area.
200         $favourites = $service->find_favourites_by_type('core_course', 'course');
201         $this->assertInternalType('array', $favourites);
202         $this->assertCount(1, $favourites); // We only get favourites for the 'core_course/course' area.
203         $this->assertAttributeEquals($fav1->id, 'id', $favourites[$fav1->id]);
205         $favourites = $service->find_favourites_by_type('core_course', 'anothertype');
206         $this->assertInternalType('array', $favourites);
207         $this->assertCount(1, $favourites); // We only get favourites for the 'core_course/course' area.
208         $this->assertAttributeEquals($fav2->id, 'id', $favourites[$fav2->id]);
209     }
211     /**
212      * Make sure the find_favourites_by_type() method only returns favourites for the scoped user.
213      */
214     public function test_find_favourites_by_type_multiple_users() {
215         list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
217         // Get a user_favourites_service for 2 users.
218         $repo = $this->get_mock_repository([]);
219         $user1service = new \core_favourites\local\service\user_favourites_service($user1context, $repo);
220         $user2service = new \core_favourites\local\service\user_favourites_service($user2context, $repo);
222         // Now, as each user, favourite the same course.
223         $fav1 = $user1service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
224         $fav2 = $user2service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
226         // Verify find_favourites_by_type only returns results for the user to which the service is scoped.
227         $user1favourites = $user1service->find_favourites_by_type('core_course', 'course');
228         $this->assertInternalType('array', $user1favourites);
229         $this->assertCount(1, $user1favourites); // We only get favourites for the 'core_course/course' area for $user1.
230         $this->assertAttributeEquals($fav1->id, 'id', $user1favourites[$fav1->id]);
232         $user2favourites = $user2service->find_favourites_by_type('core_course', 'course');
233         $this->assertInternalType('array', $user2favourites);
234         $this->assertCount(1, $user2favourites); // We only get favourites for the 'core_course/course' area for $user2.
235         $this->assertAttributeEquals($fav2->id, 'id', $user2favourites[$fav2->id]);
236     }
238     /**
239      * Test confirming that an exception is thrown if trying to get favourites for a non-existent component.
240      */
241     public function test_find_favourites_by_type_nonexistent_component() {
242         list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
244         // Get a user_favourites_service for the user.
245         $repo = $this->get_mock_repository([]);
246         $service = new \core_favourites\local\service\user_favourites_service($user1context, $repo);
248         // Verify we get an exception if we try to search for favourites in an invalid component.
249         $this->expectException('moodle_exception');
250         $service->find_favourites_by_type('cccore_notreal', 'something');
251     }
253     /**
254      * Test confirming the pagination support for the find_favourites_by_type() method.
255      */
256     public function test_find_favourites_by_type_pagination() {
257         list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
259         // Get a user_favourites_service for the user.
260         $repo = $this->get_mock_repository([]);
261         $service = new \core_favourites\local\service\user_favourites_service($user1context, $repo);
263         // Favourite 10 arbitrary items.
264         foreach (range(1, 10) as $i) {
265             $service->create_favourite('core_course', 'course', $i, $course1context);
266         }
268         // Verify we have 10 favourites.
269         $this->assertCount(10, $service->find_favourites_by_type('core_course', 'course'));
271         // Verify we get back 5 favourites for page 1.
272         $favourites = $service->find_favourites_by_type('core_course', 'course', 0, 5);
273         $this->assertCount(5, $favourites);
275         // Verify we get back 5 favourites for page 2.
276         $favourites = $service->find_favourites_by_type('core_course', 'course', 5, 5);
277         $this->assertCount(5, $favourites);
279         // Verify we get back an empty array if querying page 3.
280         $favourites = $service->find_favourites_by_type('core_course', 'course', 10, 5);
281         $this->assertCount(0, $favourites);
282     }
284     /**
285      * Test confirming the basic deletion behaviour.
286      */
287     public function test_delete_favourite_basic() {
288         list($user1context, $user2context, $course1context, $course2context) = $this->setup_users_and_courses();
290         // Get a user_favourites_service for the user.
291         $repo = $this->get_mock_repository([]);
292         $service = new \core_favourites\local\service\user_favourites_service($user1context, $repo);
294         // Favourite a course.
295         $fav1 = $service->create_favourite('core_course', 'course', $course1context->instanceid, $course1context);
296         $this->assertTrue($repo->exists($fav1->id));
298         // Delete the favourite.
299         $service->delete_favourite('core_course', 'course', $course1context->instanceid, $course1context);
301         // Verify the favourite doesn't exist.
302         $this->assertFalse($repo->exists($fav1->id));
304         // Try to delete a favourite which we know doesn't exist.
305         $this->expectException(\moodle_exception::class);
306         $service->delete_favourite('core_course', 'course', $course1context->instanceid, $course1context);
307     }