Proyectos de Subversion Moodle

Rev

Rev 11 | | Comparar con el anterior | Ultima modificación | Ver Log |

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