Proyectos de Subversion Moodle

Rev

Ir a la última revisión | | 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
/**
18
 * Steps definitions related to mod_quiz.
19
 *
20
 * @package   mod_quiz
21
 * @category  test
22
 * @copyright 2014 Marina Glancy
23
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
27
 
28
require_once(__DIR__ . '/../../../../lib/behat/behat_base.php');
29
require_once(__DIR__ . '/../../../../question/tests/behat/behat_question_base.php');
30
 
31
use Behat\Gherkin\Node\TableNode;
32
use Behat\Mink\Exception\DriverException;
33
use Behat\Mink\Exception\ExpectationException;
34
use mod_quiz\quiz_attempt;
35
use mod_quiz\quiz_settings;
36
 
37
/**
38
 * Steps definitions related to mod_quiz.
39
 *
40
 * @copyright 2014 Marina Glancy
41
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42
 */
43
class behat_mod_quiz extends behat_question_base {
44
 
45
    /**
46
     * Convert page names to URLs for steps like 'When I am on the "[page name]" page'.
47
     *
48
     * Recognised page names are:
49
     * | None so far!      |                                                              |
50
     *
51
     * @param string $page name of the page, with the component name removed e.g. 'Admin notification'.
52
     * @return moodle_url the corresponding URL.
53
     * @throws Exception with a meaningful error message if the specified page cannot be found.
54
     */
55
    protected function resolve_page_url(string $page): moodle_url {
56
        switch (strtolower($page)) {
57
            default:
58
                throw new Exception('Unrecognised quiz page type "' . $page . '."');
59
        }
60
    }
61
 
62
    /**
63
     * Convert page names to URLs for steps like 'When I am on the "[identifier]" "[page type]" page'.
64
     *
65
     * Recognised page names are:
66
     * | pagetype          | name meaning                                | description                                  |
67
     * | View              | Quiz name                                   | The quiz info page (view.php)                |
68
     * | Edit              | Quiz name                                   | The edit quiz page (edit.php)                |
69
     * | Group overrides   | Quiz name                                   | The manage group overrides page              |
70
     * | User overrides    | Quiz name                                   | The manage user overrides page               |
71
     * | Grades report     | Quiz name                                   | The overview report for a quiz               |
72
     * | Responses report  | Quiz name                                   | The responses report for a quiz              |
73
     * | Manual grading report | Quiz name                               | The manual grading report for a quiz         |
74
     * | Statistics report | Quiz name                                   | The statistics report for a quiz             |
75
     * | Attempt review    | Quiz name > username > [Attempt] attempt no | Review page for a given attempt (review.php) |
76
     * | Question bank     | Quiz name                                   | The question bank page for a quiz            |
77
     *
78
     * @param string $type identifies which type of page this is, e.g. 'Attempt review'.
79
     * @param string $identifier identifies the particular page, e.g. 'Test quiz > student > Attempt 1'.
80
     * @return moodle_url the corresponding URL.
81
     * @throws Exception with a meaningful error message if the specified page cannot be found.
82
     */
83
    protected function resolve_page_instance_url(string $type, string $identifier): moodle_url {
84
        global $DB;
85
 
86
        switch (strtolower($type)) {
87
            case 'view':
88
                return new moodle_url('/mod/quiz/view.php',
89
                        ['id' => $this->get_cm_by_quiz_name($identifier)->id]);
90
 
91
            case 'edit':
92
                return new moodle_url('/mod/quiz/edit.php',
93
                        ['cmid' => $this->get_cm_by_quiz_name($identifier)->id]);
94
 
95
            case 'multiple grades setup':
96
                return new moodle_url('/mod/quiz/editgrading.php',
97
                        ['cmid' => $this->get_cm_by_quiz_name($identifier)->id]);
98
 
99
            case 'group overrides':
100
                return new moodle_url('/mod/quiz/overrides.php',
101
                    ['cmid' => $this->get_cm_by_quiz_name($identifier)->id, 'mode' => 'group']);
102
 
103
            case 'user overrides':
104
                return new moodle_url('/mod/quiz/overrides.php',
105
                    ['cmid' => $this->get_cm_by_quiz_name($identifier)->id, 'mode' => 'user']);
106
 
107
            case 'grades report':
108
                return new moodle_url('/mod/quiz/report.php',
109
                    ['id' => $this->get_cm_by_quiz_name($identifier)->id, 'mode' => 'overview']);
110
 
111
            case 'responses report':
112
                return new moodle_url('/mod/quiz/report.php',
113
                    ['id' => $this->get_cm_by_quiz_name($identifier)->id, 'mode' => 'responses']);
114
 
115
            case 'statistics report':
116
                return new moodle_url('/mod/quiz/report.php',
117
                    ['id' => $this->get_cm_by_quiz_name($identifier)->id, 'mode' => 'statistics']);
118
 
119
            case 'manual grading report':
120
                return new moodle_url('/mod/quiz/report.php',
121
                        ['id' => $this->get_cm_by_quiz_name($identifier)->id, 'mode' => 'grading']);
122
            case 'attempt view':
123
                list($quizname, $username, $attemptno, $pageno) = explode(' > ', $identifier);
124
                $pageno = intval($pageno);
125
                $pageno = $pageno > 0 ? $pageno - 1 : 0;
126
                $attemptno = (int) trim(str_replace ('Attempt', '', $attemptno));
127
                $quiz = $this->get_quiz_by_name($quizname);
128
                $quizcm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
129
                $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
130
                $attempt = $DB->get_record('quiz_attempts',
131
                    ['quiz' => $quiz->id, 'userid' => $user->id, 'attempt' => $attemptno], '*', MUST_EXIST);
132
                return new moodle_url('/mod/quiz/attempt.php', [
133
                    'attempt' => $attempt->id,
134
                    'cmid' => $quizcm->id,
135
                    'page' => $pageno
136
                ]);
137
            case 'attempt review':
138
                if (substr_count($identifier, ' > ') !== 2) {
139
                    throw new coding_exception('For "attempt review", name must be ' .
140
                            '"{Quiz name} > {username} > Attempt {attemptnumber}", ' .
141
                            'for example "Quiz 1 > student > Attempt 1".');
142
                }
143
                list($quizname, $username, $attemptno) = explode(' > ', $identifier);
144
                $attemptno = (int) trim(str_replace ('Attempt', '', $attemptno));
145
                $quiz = $this->get_quiz_by_name($quizname);
146
                $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
147
                $attempt = $DB->get_record('quiz_attempts',
148
                        ['quiz' => $quiz->id, 'userid' => $user->id, 'attempt' => $attemptno], '*', MUST_EXIST);
149
                return new moodle_url('/mod/quiz/review.php', ['attempt' => $attempt->id]);
150
 
151
            case 'question bank':
152
                return new moodle_url('/question/edit.php', [
153
                    'cmid' => $this->get_cm_by_quiz_name($identifier)->id,
154
                ]);
155
 
156
 
157
            default:
158
                throw new Exception('Unrecognised quiz page type "' . $type . '."');
159
        }
160
    }
161
 
162
    /**
163
     * Get a quiz by name.
164
     *
165
     * @param string $name quiz name.
166
     * @return stdClass the corresponding DB row.
167
     */
168
    protected function get_quiz_by_name(string $name): stdClass {
169
        global $DB;
170
        return $DB->get_record('quiz', ['name' => $name], '*', MUST_EXIST);
171
    }
172
 
173
    /**
174
     * Get a quiz cmid from the quiz name.
175
     *
176
     * @param string $name quiz name.
177
     * @return stdClass cm from get_coursemodule_from_instance.
178
     */
179
    protected function get_cm_by_quiz_name(string $name): stdClass {
180
        $quiz = $this->get_quiz_by_name($name);
181
        return get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
182
    }
183
 
184
    /**
185
     * Put the specified questions on the specified pages of a given quiz.
186
     *
187
     * The first row should be column names:
188
     * | question | page | maxmark | requireprevious |
189
     * The first two of those are required. The others are optional.
190
     *
191
     * question        needs to uniquely match a question name.
192
     * page            is a page number. Must start at 1, and on each following
193
     *                 row should be the same as the previous, or one more.
194
     * maxmark         What the question is marked out of. Defaults to question.defaultmark.
195
     * requireprevious The question can only be attempted after the previous one was completed.
196
     *
197
     * Then there should be a number of rows of data, one for each question you want to add.
198
     *
199
     * For backwards-compatibility reasons, specifying the column names is optional
200
     * (but strongly encouraged). If not specified, the columns are asseumed to be
201
     * | question | page | maxmark |.
202
     *
203
     * @param string $quizname the name of the quiz to add questions to.
204
     * @param TableNode $data information about the questions to add.
205
     *
206
     * @Given /^quiz "([^"]*)" contains the following questions:$/
207
     */
208
    public function quiz_contains_the_following_questions($quizname, TableNode $data) {
209
        global $DB;
210
 
211
        $quiz = $this->get_quiz_by_name($quizname);
212
 
213
        // Deal with backwards-compatibility, optional first row.
214
        $firstrow = $data->getRow(0);
215
        if (!in_array('question', $firstrow) && !in_array('page', $firstrow)) {
216
            if (count($firstrow) == 2) {
217
                $headings = ['question', 'page'];
218
            } else if (count($firstrow) == 3) {
219
                $headings = ['question', 'page', 'maxmark'];
220
            } else {
221
                throw new ExpectationException('When adding questions to a quiz, you should give 2 or three 3 things: ' .
222
                        ' the question name, the page number, and optionally the maximum mark. ' .
223
                        count($firstrow) . ' values passed.', $this->getSession());
224
            }
225
            $rows = $data->getRows();
226
            array_unshift($rows, $headings);
227
            $data = new TableNode($rows);
228
        }
229
 
230
        // Add the questions.
231
        $lastpage = 0;
232
        foreach ($data->getHash() as $questiondata) {
233
            if (!array_key_exists('question', $questiondata)) {
234
                throw new ExpectationException('When adding questions to a quiz, ' .
235
                        'the question name column is required.', $this->getSession());
236
            }
237
            if (!array_key_exists('page', $questiondata)) {
238
                throw new ExpectationException('When adding questions to a quiz, ' .
239
                        'the page number column is required.', $this->getSession());
240
            }
241
 
242
            // Question id, category and type.
243
            $sql = 'SELECT q.id AS id, qbe.questioncategoryid AS category, q.qtype AS qtype
244
                      FROM {question} q
245
                      JOIN {question_versions} qv ON qv.questionid = q.id
246
                      JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
247
                     WHERE q.name = :name';
248
            $question = $DB->get_record_sql($sql, ['name' => $questiondata['question']], MUST_EXIST);
249
 
250
            // Page number.
251
            $page = clean_param($questiondata['page'], PARAM_INT);
252
            if ($page <= 0 || (string) $page !== $questiondata['page']) {
253
                throw new ExpectationException('The page number for question "' .
254
                         $questiondata['question'] . '" must be a positive integer.',
255
                        $this->getSession());
256
            }
257
            if ($page < $lastpage || $page > $lastpage + 1) {
258
                throw new ExpectationException('When adding questions to a quiz, ' .
259
                        'the page number for each question must either be the same, ' .
260
                        'or one more, then the page number for the previous question.',
261
                        $this->getSession());
262
            }
263
            $lastpage = $page;
264
 
265
            // Max mark.
266
            if (!array_key_exists('maxmark', $questiondata) || $questiondata['maxmark'] === '') {
267
                $maxmark = null;
268
            } else {
269
                $maxmark = clean_param($questiondata['maxmark'], PARAM_LOCALISEDFLOAT);
270
                if (!is_numeric($maxmark) || $maxmark < 0) {
271
                    throw new ExpectationException('The max mark for question "' .
272
                            $questiondata['question'] . '" must be a positive number.',
273
                            $this->getSession());
274
                }
275
            }
276
 
277
            if ($question->qtype == 'random') {
278
                if (!array_key_exists('includingsubcategories', $questiondata) || $questiondata['includingsubcategories'] === '') {
279
                    $includingsubcategories = false;
280
                } else {
281
                    $includingsubcategories = clean_param($questiondata['includingsubcategories'], PARAM_BOOL);
282
                }
283
 
284
                $filter = [
285
                    'category' => [
286
                        'jointype' => \qbank_managecategories\category_condition::JOINTYPE_DEFAULT,
287
                        'values' => [$question->category],
288
                        'filteroptions' => ['includesubcategories' => $includingsubcategories],
289
                    ],
290
                ];
291
                $filtercondition['filter'] = $filter;
292
                $settings = quiz_settings::create($quiz->id);
293
                $structure = \mod_quiz\structure::create_for_quiz($settings);
294
                $structure->add_random_questions($page, 1, $filtercondition);
295
            } else {
296
                // Add the question.
297
                quiz_add_quiz_question($question->id, $quiz, $page, $maxmark);
298
            }
299
 
300
            // Look for additional properties we might want to set on the new slot.
301
            $extraslotproperties = [];
302
 
303
            // Display number (allowing editable customised question number).
304
            if (array_key_exists('displaynumber', $questiondata)) {
305
                if (!is_number($questiondata['displaynumber']) && !is_string($questiondata['displaynumber'])) {
306
                    throw new ExpectationException('Displayed question number for "' . $questiondata['question'] .
307
                            '" should either be \'i\', automatically numbered (eg. 1, 2, 3),
308
                            or customised (eg. A.1, A.2, 1.1, 1.2)', $this->getSession());
309
                }
310
                $extraslotproperties['displaynumber'] = $questiondata['displaynumber'];
311
            }
312
 
313
            // Require previous.
314
            if (array_key_exists('requireprevious', $questiondata)) {
315
                if ($questiondata['requireprevious'] === '1') {
316
                    $extraslotproperties['requireprevious'] = 1;
317
                } else if ($questiondata['requireprevious'] !== '' && $questiondata['requireprevious'] !== '0') {
318
                    throw new ExpectationException('Require previous for question "' .
319
                        $questiondata['question'] . '" should be 0, 1 or blank.',
320
                        $this->getSession());
321
                }
322
            }
323
 
324
            // Grade item.
325
            if (array_key_exists('grade item', $questiondata) && trim($questiondata['grade item']) !== '') {
326
                $extraslotproperties['quizgradeitemid'] =
327
                    $DB->get_field('quiz_grade_items', 'id',
328
                        ['quizid' => $quiz->id, 'name' => $questiondata['grade item']], MUST_EXIST);
329
            }
330
 
331
            // If there were any extra properties, save them.
332
            if ($extraslotproperties) {
333
                // We assume that the slot was just created for this row of data is the highest numbered one.
334
                $extraslotproperties['id'] = $DB->get_field('quiz_slots', 'MAX(id)', ['quizid' => $quiz->id]);
335
 
336
                $DB->update_record('quiz_slots', $extraslotproperties);
337
            }
338
        }
339
 
340
        $quizobj = quiz_settings::create($quiz->id);
341
        $quizobj->get_grade_calculator()->recompute_quiz_sumgrades();
342
    }
343
 
344
    /**
345
     * Put the specified section headings to start at specified pages of a given quiz.
346
     *
347
     * The first row should be column names:
348
     * | heading | firstslot | shufflequestions |
349
     *
350
     * heading   is the section heading text
351
     * firstslot is the slot number where the section starts
352
     * shuffle   whether this section is shuffled (0 or 1)
353
     *
354
     * Then there should be a number of rows of data, one for each section you want to add.
355
     *
356
     * @param string $quizname the name of the quiz to add sections to.
357
     * @param TableNode $data information about the sections to add.
358
     *
359
     * @Given /^quiz "([^"]*)" contains the following sections:$/
360
     */
361
    public function quiz_contains_the_following_sections($quizname, TableNode $data) {
362
        global $DB;
363
 
364
        $quiz = $DB->get_record('quiz', ['name' => $quizname], '*', MUST_EXIST);
365
 
366
        // Add the sections.
367
        $previousfirstslot = 0;
368
        foreach ($data->getHash() as $rownumber => $sectiondata) {
369
            if (!array_key_exists('heading', $sectiondata)) {
370
                throw new ExpectationException('When adding sections to a quiz, ' .
371
                        'the heading name column is required.', $this->getSession());
372
            }
373
            if (!array_key_exists('firstslot', $sectiondata)) {
374
                throw new ExpectationException('When adding sections to a quiz, ' .
375
                        'the firstslot name column is required.', $this->getSession());
376
            }
377
            if (!array_key_exists('shuffle', $sectiondata)) {
378
                throw new ExpectationException('When adding sections to a quiz, ' .
379
                        'the shuffle name column is required.', $this->getSession());
380
            }
381
 
382
            if ($rownumber == 0) {
383
                $section = $DB->get_record('quiz_sections', ['quizid' => $quiz->id], '*', MUST_EXIST);
384
            } else {
385
                $section = new stdClass();
386
                $section->quizid = $quiz->id;
387
            }
388
 
389
            // Heading.
390
            $section->heading = $sectiondata['heading'];
391
 
392
            // First slot.
393
            $section->firstslot = clean_param($sectiondata['firstslot'], PARAM_INT);
394
            if ($section->firstslot <= $previousfirstslot ||
395
                    (string) $section->firstslot !== $sectiondata['firstslot']) {
396
                throw new ExpectationException('The firstslot number for section "' .
397
                        $sectiondata['heading'] . '" must an integer greater than the previous section firstslot.',
398
                        $this->getSession());
399
            }
400
            if ($rownumber == 0 && $section->firstslot != 1) {
401
                throw new ExpectationException('The first section must have firstslot set to 1.',
402
                        $this->getSession());
403
            }
404
 
405
            // Shuffle.
406
            $section->shufflequestions = clean_param($sectiondata['shuffle'], PARAM_INT);
407
            if ((string) $section->shufflequestions !== $sectiondata['shuffle']) {
408
                throw new ExpectationException('The shuffle value for section "' .
409
                        $sectiondata['heading'] . '" must be 0 or 1.',
410
                        $this->getSession());
411
            }
412
 
413
            if ($rownumber == 0) {
414
                $DB->update_record('quiz_sections', $section);
415
            } else {
416
                $DB->insert_record('quiz_sections', $section);
417
            }
418
        }
419
 
420
        if ($section->firstslot > $DB->count_records('quiz_slots', ['quizid' => $quiz->id])) {
421
            throw new ExpectationException('The section firstslot must be less than the total number of slots in the quiz.',
422
                    $this->getSession());
423
        }
424
    }
425
 
426
    /**
427
     * Adds a question to the existing quiz with filling the form.
428
     *
429
     * The form for creating a question should be on one page.
430
     *
431
     * @When /^I add a "(?P<question_type_string>(?:[^"]|\\")*)" question to the "(?P<quiz_name_string>(?:[^"]|\\")*)" quiz with:$/
432
     * @param string $questiontype
433
     * @param string $quizname
434
     * @param TableNode $questiondata with data for filling the add question form
435
     */
436
    public function i_add_question_to_the_quiz_with($questiontype, $quizname, TableNode $questiondata) {
437
        $quizname = $this->escape($quizname);
438
        $addaquestion = $this->escape(get_string('addaquestion', 'quiz'));
439
 
440
        $this->execute('behat_navigation::i_am_on_page_instance', [
441
            $quizname,
442
            'mod_quiz > Edit',
443
        ]);
444
 
445
        if ($this->running_javascript()) {
446
            $this->execute("behat_action_menu::i_open_the_action_menu_in", ['.slots', "css_element"]);
447
            $this->execute("behat_action_menu::i_choose_in_the_open_action_menu", [$addaquestion]);
448
        } else {
449
            $this->execute('behat_general::click_link', $addaquestion);
450
        }
451
 
452
        $this->finish_adding_question($questiontype, $questiondata);
453
    }
454
 
455
    /**
456
     * Set the max mark for a question on the Edit quiz page.
457
     *
458
     * @When /^I set the max mark for question "(?P<question_name_string>(?:[^"]|\\")*)" to "(?P<new_mark_string>(?:[^"]|\\")*)"$/
459
     * @param string $questionname the name of the question to set the max mark for.
460
     * @param string $newmark the mark to set
461
     */
462
    public function i_set_the_max_mark_for_quiz_question($questionname, $newmark) {
463
        $this->execute('behat_general::click_link', $this->escape(get_string('editmaxmark', 'quiz')));
464
 
465
        $this->execute('behat_general::wait_until_exists', ["li input[name=maxmark]", "css_element"]);
466
 
467
        $this->execute('behat_general::assert_page_contains_text', $this->escape(get_string('edittitleinstructions')));
468
 
469
        $this->execute('behat_general::i_type', [$newmark]);
470
        $this->execute('behat_general::i_press_named_key', ['', 'enter']);
471
    }
472
 
473
    /**
474
     * Open the add menu on a given page, or at the end of the Edit quiz page.
475
     * @Given /^I open the "(?P<page_n_or_last_string>(?:[^"]|\\")*)" add to quiz menu$/
476
     * @param string $pageorlast either "Page n" or "last".
477
     */
478
    public function i_open_the_add_to_quiz_menu_for($pageorlast) {
479
 
480
        if (!$this->running_javascript()) {
481
            throw new DriverException('Activities actions menu not available when Javascript is disabled');
482
        }
483
 
484
        if ($pageorlast == 'last') {
485
            $xpath = "//div[@class = 'last-add-menu']//a[contains(@data-toggle, 'dropdown') and contains(., 'Add')]";
486
        } else if (preg_match('~Page (\d+)~', $pageorlast, $matches)) {
487
            $xpath = "//li[@id = 'page-{$matches[1]}']//a[contains(@data-toggle, 'dropdown') and contains(., 'Add')]";
488
        } else {
489
            throw new ExpectationException("The I open the add to quiz menu step must specify either 'Page N' or 'last'.",
490
                $this->getSession());
491
        }
492
        $this->find('xpath', $xpath)->click();
493
    }
494
 
495
    /**
496
     * Check whether a particular question is on a particular page of the quiz on the Edit quiz page.
497
     * @Given /^I should see "(?P<question_name>(?:[^"]|\\")*)" on quiz page "(?P<page_number>\d+)"$/
498
     * @param string $questionname the name of the question we are looking for.
499
     * @param number $pagenumber the page it should be found on.
500
     */
501
    public function i_should_see_on_quiz_page($questionname, $pagenumber) {
502
        $xpath = "//li[contains(., '" . $this->escape($questionname) .
503
            "')][./preceding-sibling::li[contains(@class, 'pagenumber')][1][contains(., 'Page " .
504
            $pagenumber . "')]]";
505
 
506
        $this->execute('behat_general::should_exist', [$xpath, 'xpath_element']);
507
    }
508
 
509
    /**
510
     * Check whether a particular question is not on a particular page of the quiz on the Edit quiz page.
511
     * @Given /^I should not see "(?P<question_name>(?:[^"]|\\")*)" on quiz page "(?P<page_number>\d+)"$/
512
     * @param string $questionname the name of the question we are looking for.
513
     * @param number $pagenumber the page it should be found on.
514
     */
515
    public function i_should_not_see_on_quiz_page($questionname, $pagenumber) {
516
        $xpath = "//li[contains(., '" . $this->escape($questionname) .
517
                "')][./preceding-sibling::li[contains(@class, 'pagenumber')][1][contains(., 'Page " .
518
                $pagenumber . "')]]";
519
 
520
        $this->execute('behat_general::should_not_exist', [$xpath, 'xpath_element']);
521
    }
522
 
523
    /**
524
     * Check whether one question comes before another on the Edit quiz page.
525
     * The two questions must be on the same page.
526
     * @Given /^I should see "(?P<first_q_name>(?:[^"]|\\")*)" before "(?P<second_q_name>(?:[^"]|\\")*)" on the edit quiz page$/
527
     * @param string $firstquestionname the name of the question that should come first in order.
528
     * @param string $secondquestionname the name of the question that should come immediately after it in order.
529
     */
530
    public function i_should_see_before_on_the_edit_quiz_page($firstquestionname, $secondquestionname) {
531
        $xpath = "//li[contains(., '" . $this->escape($firstquestionname) .
532
                "')]/following-sibling::li" .
533
                "[contains(., '" . $this->escape($secondquestionname) . "')]";
534
 
535
        $this->execute('behat_general::should_exist', [$xpath, 'xpath_element']);
536
    }
537
 
538
    /**
539
     * Check the number displayed alongside a question on the Edit quiz page.
540
     * @Given /^"(?P<question_name>(?:[^"]|\\")*)" should have number "(?P<number>(?:[^"]|\\")*)" on the edit quiz page$/
541
     * @param string $questionname the name of the question we are looking for.
542
     * @param number $number the number (or 'i') that should be displayed beside that question.
543
     */
544
    public function should_have_number_on_the_edit_quiz_page($questionname, $number) {
545
        if ($number !== get_string('infoshort', 'quiz')) {
546
            // Logic here copied from edit_renderer, which is not ideal, but necessary.
547
            $number = get_string('question') . ' ' . $number;
548
        }
549
        $xpath = "//li[contains(@class, 'slot') and contains(., '" . $this->escape($questionname) .
550
                "')]//span[contains(@class, 'slotnumber') and normalize-space(.) = '" . $this->escape($number) . "']";
551
        $this->execute('behat_general::should_exist', [$xpath, 'xpath_element']);
552
    }
553
 
554
    /**
555
     * Get the xpath for a partcular add/remove page-break icon.
556
     * @param string $addorremoves 'Add' or 'Remove'.
557
     * @param string $questionname the name of the question before the icon.
558
     * @return string the requried xpath.
559
     */
560
    protected function get_xpath_page_break_icon_after_question($addorremoves, $questionname) {
561
        return "//li[contains(@class, 'slot') and contains(., '" . $this->escape($questionname) .
562
                "')]//a[contains(@class, 'page_split_join') and @title = '" . $addorremoves . " page break']";
563
    }
564
 
565
    /**
566
     * Click the add or remove page-break icon after a particular question.
567
     * @When /^I click on the "(Add|Remove)" page break icon after question "(?P<question_name>(?:[^"]|\\")*)"$/
568
     * @param string $addorremoves 'Add' or 'Remove'.
569
     * @param string $questionname the name of the question before the icon to click.
570
     */
571
    public function i_click_on_the_page_break_icon_after_question($addorremoves, $questionname) {
572
        $xpath = $this->get_xpath_page_break_icon_after_question($addorremoves, $questionname);
573
 
574
        $this->execute("behat_general::i_click_on", [$xpath, "xpath_element"]);
575
    }
576
 
577
    /**
578
     * Assert the add or remove page-break icon after a particular question exists.
579
     * @When /^the "(Add|Remove)" page break icon after question "(?P<question_name>(?:[^"]|\\")*)" should exist$/
580
     * @param string $addorremoves 'Add' or 'Remove'.
581
     * @param string $questionname the name of the question before the icon to click.
582
     * @return array of steps.
583
     */
584
    public function the_page_break_icon_after_question_should_exist($addorremoves, $questionname) {
585
        $xpath = $this->get_xpath_page_break_icon_after_question($addorremoves, $questionname);
586
 
587
        $this->execute('behat_general::should_exist', [$xpath, 'xpath_element']);
588
    }
589
 
590
    /**
591
     * Assert the add or remove page-break icon after a particular question does not exist.
592
     * @When /^the "(Add|Remove)" page break icon after question "(?P<question_name>(?:[^"]|\\")*)" should not exist$/
593
     * @param string $addorremoves 'Add' or 'Remove'.
594
     * @param string $questionname the name of the question before the icon to click.
595
     * @return array of steps.
596
     */
597
    public function the_page_break_icon_after_question_should_not_exist($addorremoves, $questionname) {
598
        $xpath = $this->get_xpath_page_break_icon_after_question($addorremoves, $questionname);
599
 
600
        $this->execute('behat_general::should_not_exist', [$xpath, 'xpath_element']);
601
    }
602
 
603
    /**
604
     * Check the add or remove page-break link after a particular question contains the given parameters in its url.
605
     *
606
     * @When /^the "(Add|Remove)" page break link after question "(?P<question_name>(?:[^"]|\\")*) should contain:$/
607
     * @When /^the "(Add|Remove)" page break link after question "(?P<question_name>(?:[^"]|\\")*) should contain:"$/
608
     * @param string $addorremoves 'Add' or 'Remove'.
609
     * @param string $questionname the name of the question before the icon to click.
610
     * @param TableNode $paramdata with data for checking the page break url
611
     * @return array of steps.
612
     */
613
    public function the_page_break_link_after_question_should_contain($addorremoves, $questionname, $paramdata) {
614
        $xpath = $this->get_xpath_page_break_icon_after_question($addorremoves, $questionname);
615
 
616
        $this->execute("behat_general::i_click_on", [$xpath, "xpath_element"]);
617
    }
618
 
619
    /**
620
     * Set Shuffle for shuffling questions within sections
621
     *
622
     * @param string $heading the heading of the section to change shuffle for.
623
     *
624
     * @Given /^I click on shuffle for section "([^"]*)" on the quiz edit page$/
625
     */
626
    public function i_click_on_shuffle_for_section($heading) {
627
        $xpath = $this->get_xpath_for_shuffle_checkbox($heading);
628
        $checkbox = $this->find('xpath', $xpath);
629
        $this->ensure_node_is_visible($checkbox);
630
        $checkbox->click();
631
    }
632
 
633
    /**
634
     * Check the shuffle checkbox for a particular section.
635
     *
636
     * @param string $heading the heading of the section to check shuffle for
637
     * @param int $value whether the shuffle checkbox should be on or off.
638
     *
639
     * @Given /^shuffle for section "([^"]*)" should be "(On|Off)" on the quiz edit page$/
640
     */
641
    public function shuffle_for_section_should_be($heading, $value) {
642
        $xpath = $this->get_xpath_for_shuffle_checkbox($heading);
643
        $checkbox = $this->find('xpath', $xpath);
644
        $this->ensure_node_is_visible($checkbox);
645
        if ($value == 'On' && !$checkbox->isChecked()) {
646
            $msg = "Shuffle for section '$heading' is not checked, but you are expecting it to be checked ($value). " .
647
                    "Check the line with: \nshuffle for section \"$heading\" should be \"$value\" on the quiz edit page" .
648
                    "\nin your behat script";
649
            throw new ExpectationException($msg, $this->getSession());
650
        } else if ($value == 'Off' && $checkbox->isChecked()) {
651
            $msg = "Shuffle for section '$heading' is checked, but you are expecting it not to be ($value). " .
652
                    "Check the line with: \nshuffle for section \"$heading\" should be \"$value\" on the quiz edit page" .
653
                    "\nin your behat script";
654
            throw new ExpectationException($msg, $this->getSession());
655
        }
656
    }
657
 
658
    /**
659
     * Return the xpath for shuffle checkbox in section heading
660
     * @param string $heading
661
     * @return string
662
     */
663
    protected function get_xpath_for_shuffle_checkbox($heading) {
664
         return "//div[contains(@class, 'section-heading') and contains(., '" . $this->escape($heading) .
665
                "')]//input[@type = 'checkbox']";
666
    }
667
 
668
    /**
669
     * Move a question on the Edit quiz page by first clicking on the Move icon,
670
     * then clicking one of the "After ..." links.
671
     * @When /^I move "(?P<question_name>(?:[^"]|\\")*)" to "(?P<target>(?:[^"]|\\")*)" in the quiz by clicking the move icon$/
672
     * @param string $questionname the name of the question we are looking for.
673
     * @param string $target the target place to move to. One of the links in the pop-up like
674
     *      "After Page 1" or "After Question N".
675
     */
676
    public function i_move_question_after_item_by_clicking_the_move_icon($questionname, $target) {
677
        $iconxpath = "//li[contains(@class, ' slot ') and contains(., '" . $this->escape($questionname) .
678
                "')]//span[contains(@class, 'editing_move')]";
679
 
680
        $this->execute("behat_general::i_click_on", [$iconxpath, "xpath_element"]);
681
        $this->execute("behat_general::i_click_on", [$this->escape($target), "button"]);
682
    }
683
 
684
    /**
685
     * Move a question on the Edit quiz page by dragging a given question on top of another item.
686
     * @When /^I move "(?P<question_name>(?:[^"]|\\")*)" to "(?P<target>(?:[^"]|\\")*)" in the quiz by dragging$/
687
     * @param string $questionname the name of the question we are looking for.
688
     * @param string $target the target place to move to. Ether a question name, or "Page N"
689
     */
690
    public function i_move_question_after_item_by_dragging($questionname, $target) {
691
        $iconxpath = "//li[contains(@class, ' slot ') and contains(., '" . $this->escape($questionname) .
692
                "')]//span[contains(@class, 'editing_move')]//img";
693
        $destinationxpath = "//li[contains(@class, ' slot ') or contains(@class, 'pagenumber ')]" .
694
                "[contains(., '" . $this->escape($target) . "')]";
695
 
696
        $this->execute('behat_general::i_drag_and_i_drop_it_in',
697
            [$iconxpath, 'xpath_element', $destinationxpath, 'xpath_element']
698
        );
699
    }
700
 
701
    /**
702
     * Delete a question on the Edit quiz page by first clicking on the Delete icon,
703
     * then clicking one of the "After ..." links.
704
     * @When /^I delete "(?P<question_name>(?:[^"]|\\")*)" in the quiz by clicking the delete icon$/
705
     * @param string $questionname the name of the question we are looking for.
706
     * @return array of steps.
707
     */
708
    public function i_delete_question_by_clicking_the_delete_icon($questionname) {
709
        $slotxpath = "//li[contains(@class, ' slot ') and contains(., '" . $this->escape($questionname) .
710
                "')]";
711
        $deletexpath = "//a[contains(@class, 'editing_delete')]";
712
 
713
        $this->execute("behat_general::i_click_on", [$slotxpath . $deletexpath, "xpath_element"]);
714
 
715
        $this->execute('behat_general::i_click_on_in_the',
716
            ['Yes', "button", "Confirm", "dialogue"]
717
        );
718
    }
719
 
720
    /**
721
     * Set the section heading for a given section on the Edit quiz page
722
     *
723
     * @When /^I change quiz section heading "(?P<section_name_string>(?:[^"]|\\")*)" to "(?P<new_section_heading_string>(?:[^"]|\\")*)"$/
724
     * @param string $sectionname the heading to change.
725
     * @param string $sectionheading the new heading to set.
726
     */
727
    public function i_set_the_section_heading_for($sectionname, $sectionheading) {
728
        // Empty section headings will have a default names of "Untitled heading".
729
        if (empty($sectionname)) {
730
            $sectionname = get_string('sectionnoname', 'quiz');
731
        }
732
        $this->execute('behat_general::click_link', $this->escape("Edit heading '{$sectionname}'"));
733
 
734
        $this->execute('behat_general::assert_page_contains_text', $this->escape(get_string('edittitleinstructions')));
735
 
736
        $this->execute('behat_general::i_press_named_key', ['', 'backspace']);
737
        $this->execute('behat_general::i_type', [$sectionheading]);
738
        $this->execute('behat_general::i_press_named_key', ['', 'enter']);
739
    }
740
 
741
    /**
742
     * Check that a given question comes after a given section heading in the
743
     * quiz navigation block.
744
     *
745
     * @Then /^I should see question "(?P<questionnumber>(?:[^"]|\\")*)" in section "(?P<section_heading_string>(?:[^"]|\\")*)" in the quiz navigation$/
746
     * @param string $questionnumber the number of the question to check.
747
     * @param string $sectionheading which section heading it should appear after.
748
     */
749
    public function i_should_see_question_in_section_in_the_quiz_navigation($questionnumber, $sectionheading) {
750
 
751
        // Using xpath literal to avoid quotes problems.
752
        $questionnumberliteral = behat_context_helper::escape($questionnumber);
753
        $headingliteral = behat_context_helper::escape($sectionheading);
754
 
755
        // Split in two checkings to give more feedback in case of exception.
756
        $exception = new ExpectationException('Question "' . $questionnumber . '" is not in section "' .
757
                $sectionheading . '" in the quiz navigation.', $this->getSession());
758
        $xpath = "//*[@id = 'mod_quiz_navblock']//*[contains(concat(' ', normalize-space(@class), ' '), ' qnbutton ') and " .
759
                "contains(., {$questionnumberliteral}) and contains(preceding-sibling::h3[1], {$headingliteral})]";
760
        $this->find('xpath', $xpath, $exception);
761
    }
762
 
763
    /**
764
     * Helper used by user_has_attempted_with_responses,
765
     * user_has_started_an_attempt_at_quiz_with_details, etc.
766
     *
767
     * @param TableNode $attemptinfo data table from the Behat step
768
     * @return array with two elements, $forcedrandomquestions, $forcedvariants,
769
     *      that can be passed to $quizgenerator->create_attempt.
770
     */
771
    protected function extract_forced_randomisation_from_attempt_info(TableNode $attemptinfo) {
772
        global $DB;
773
 
774
        $forcedrandomquestions = [];
775
        $forcedvariants = [];
776
        foreach ($attemptinfo->getHash() as $slotinfo) {
777
            if (empty($slotinfo['slot'])) {
778
                throw new ExpectationException('When simulating a quiz attempt, ' .
779
                        'the slot column is required.', $this->getSession());
780
            }
781
 
782
            if (!empty($slotinfo['actualquestion'])) {
783
                $forcedrandomquestions[$slotinfo['slot']] = $DB->get_field('question', 'id',
784
                        ['name' => $slotinfo['actualquestion']], MUST_EXIST);
785
            }
786
 
787
            if (!empty($slotinfo['variant'])) {
788
                $forcedvariants[$slotinfo['slot']] = (int) $slotinfo['variant'];
789
            }
790
        }
791
        return [$forcedrandomquestions, $forcedvariants];
792
    }
793
 
794
    /**
795
     * Helper used by user_has_attempted_with_responses, user_has_checked_answers_in_their_attempt_at_quiz,
796
     * user_has_input_answers_in_their_attempt_at_quiz, etc.
797
     *
798
     * @param TableNode $attemptinfo data table from the Behat step
799
     * @return array of responses that can be passed to $quizgenerator->submit_responses.
800
     */
801
    protected function extract_responses_from_attempt_info(TableNode $attemptinfo) {
802
        $responses = [];
803
        foreach ($attemptinfo->getHash() as $slotinfo) {
804
            if (empty($slotinfo['slot'])) {
805
                throw new ExpectationException('When simulating a quiz attempt, ' .
806
                        'the slot column is required.', $this->getSession());
807
            }
808
            if (!array_key_exists('response', $slotinfo)) {
809
                throw new ExpectationException('When simulating a quiz attempt, ' .
810
                        'the response column is required.', $this->getSession());
811
            }
812
            $responses[$slotinfo['slot']] = $slotinfo['response'];
813
        }
814
        return $responses;
815
    }
816
 
817
    /**
818
     * Attempt a quiz.
819
     *
820
     * The first row should be column names:
821
     * | slot | actualquestion | variant | response |
822
     * The first two of those are required. The others are optional.
823
     *
824
     * slot           The slot
825
     * actualquestion This column is optional, and is only needed if the quiz contains
826
     *                random questions. If so, this will let you control which actual
827
     *                question gets picked when this slot is 'randomised' at the
828
     *                start of the attempt. If you don't specify, then one will be picked
829
     *                at random (which might make the response meaningless).
830
     *                Give the question name.
831
     * variant        This column is similar, and also options. It is only needed if
832
     *                the question that ends up in this slot returns something greater
833
     *                than 1 for $question->get_num_variants(). Like with actualquestion,
834
     *                if you specify a value here it is used the fix the 'random' choice
835
     *                made when the quiz is started.
836
     * response       The response that was submitted. How this is interpreted depends on
837
     *                the question type. It gets passed to
838
     *                {@link core_question_generator::get_simulated_post_data_for_question_attempt()}
839
     *                and therefore to the un_summarise_response method of the question to decode.
840
     *
841
     * Then there should be a number of rows of data, one for each question you want to add.
842
     * There is no need to supply answers to all questions. If so, other qusetions will be
843
     * left unanswered.
844
     *
845
     * @param string $username the username of the user that will attempt.
846
     * @param string $quizname the name of the quiz the user will attempt.
847
     * @param TableNode $attemptinfo information about the questions to add, as above.
848
     * @Given /^user "([^"]*)" has attempted "([^"]*)" with responses:$/
849
     */
850
    public function user_has_attempted_with_responses($username, $quizname, TableNode $attemptinfo) {
851
        global $DB;
852
 
853
        /** @var mod_quiz_generator $quizgenerator */
854
        $quizgenerator = behat_util::get_data_generator()->get_plugin_generator('mod_quiz');
855
 
856
        $quizid = $DB->get_field('quiz', 'id', ['name' => $quizname], MUST_EXIST);
857
        $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
858
 
859
        list($forcedrandomquestions, $forcedvariants) =
860
                $this->extract_forced_randomisation_from_attempt_info($attemptinfo);
861
        $responses = $this->extract_responses_from_attempt_info($attemptinfo);
862
 
863
        $this->set_user($user);
864
 
865
        $attempt = $quizgenerator->create_attempt($quizid, $user->id,
866
                $forcedrandomquestions, $forcedvariants);
867
 
868
        $quizgenerator->submit_responses($attempt->id, $responses, false, true);
869
 
870
        $this->set_user();
871
    }
872
 
873
    /**
874
     * Start a quiz attempt without answers.
875
     *
876
     * @param string $username the username of the user that will attempt.
877
     * @param string $quizname the name of the quiz the user will attempt.
878
     * @Given /^user "([^"]*)" has started an attempt at quiz "([^"]*)"$/
879
     */
880
    public function user_has_started_an_attempt_at_quiz($username, $quizname) {
881
        global $DB;
882
 
883
        /** @var mod_quiz_generator $quizgenerator */
884
        $quizgenerator = behat_util::get_data_generator()->get_plugin_generator('mod_quiz');
885
 
886
        $quizid = $DB->get_field('quiz', 'id', ['name' => $quizname], MUST_EXIST);
887
        $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
888
        $this->set_user($user);
889
        $quizgenerator->create_attempt($quizid, $user->id);
890
        $this->set_user();
891
    }
892
 
893
    /**
894
     * Start a quiz attempt without answers.
895
     *
896
     * The supplied data table for have a row for each slot where you want
897
     * to force either which random question was chose, or which random variant
898
     * was used, as for {@link user_has_attempted_with_responses()} above.
899
     *
900
     * @param string $username the username of the user that will attempt.
901
     * @param string $quizname the name of the quiz the user will attempt.
902
     * @param TableNode $attemptinfo information about the questions to add, as above.
903
     * @Given /^user "([^"]*)" has started an attempt at quiz "([^"]*)" randomised as follows:$/
904
     */
905
    public function user_has_started_an_attempt_at_quiz_with_details($username, $quizname, TableNode $attemptinfo) {
906
        global $DB;
907
 
908
        /** @var mod_quiz_generator $quizgenerator */
909
        $quizgenerator = behat_util::get_data_generator()->get_plugin_generator('mod_quiz');
910
 
911
        $quizid = $DB->get_field('quiz', 'id', ['name' => $quizname], MUST_EXIST);
912
        $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
913
 
914
        list($forcedrandomquestions, $forcedvariants) =
915
                $this->extract_forced_randomisation_from_attempt_info($attemptinfo);
916
 
917
        $this->set_user($user);
918
 
919
        $quizgenerator->create_attempt($quizid, $user->id,
920
                $forcedrandomquestions, $forcedvariants);
921
 
922
        $this->set_user();
923
    }
924
 
925
    /**
926
     * Input answers to particular questions an existing quiz attempt, without
927
     * simulating a click of the 'Check' button, if any.
928
     *
929
     * Then there should be a number of rows of data, with two columns slot and response,
930
     * as for {@link user_has_attempted_with_responses()} above.
931
     * There is no need to supply answers to all questions. If so, other questions will be
932
     * left unanswered.
933
     *
934
     * @param string $username the username of the user that will attempt.
935
     * @param string $quizname the name of the quiz the user will attempt.
936
     * @param TableNode $attemptinfo information about the questions to add, as above.
937
     * @throws \Behat\Mink\Exception\ExpectationException
938
     * @Given /^user "([^"]*)" has input answers in their attempt at quiz "([^"]*)":$/
939
     */
940
    public function user_has_input_answers_in_their_attempt_at_quiz($username, $quizname, TableNode $attemptinfo) {
941
        global $DB;
942
 
943
        /** @var mod_quiz_generator $quizgenerator */
944
        $quizgenerator = behat_util::get_data_generator()->get_plugin_generator('mod_quiz');
945
 
946
        $quizid = $DB->get_field('quiz', 'id', ['name' => $quizname], MUST_EXIST);
947
        $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
948
 
949
        $responses = $this->extract_responses_from_attempt_info($attemptinfo);
950
 
951
        $this->set_user($user);
952
 
953
        $attempts = quiz_get_user_attempts($quizid, $user->id, 'unfinished', true);
954
        $quizgenerator->submit_responses(key($attempts), $responses, false, false);
955
 
956
        $this->set_user();
957
    }
958
 
959
    /**
960
     * Submit answers to questions an existing quiz attempt, with a simulated click on the 'Check' button.
961
     *
962
     * This step should only be used with question behaviours that have have
963
     * a 'Check' button. Those include Interactive with multiple tires, Immediate feedback
964
     * and Immediate feedback with CBM.
965
     *
966
     * Then there should be a number of rows of data, with two columns slot and response,
967
     * as for {@link user_has_attempted_with_responses()} above.
968
     * There is no need to supply answers to all questions. If so, other questions will be
969
     * left unanswered.
970
     *
971
     * @param string $username the username of the user that will attempt.
972
     * @param string $quizname the name of the quiz the user will attempt.
973
     * @param TableNode $attemptinfo information about the questions to add, as above.
974
     * @throws \Behat\Mink\Exception\ExpectationException
975
     * @Given /^user "([^"]*)" has checked answers in their attempt at quiz "([^"]*)":$/
976
     */
977
    public function user_has_checked_answers_in_their_attempt_at_quiz($username, $quizname, TableNode $attemptinfo) {
978
        global $DB;
979
 
980
        /** @var mod_quiz_generator $quizgenerator */
981
        $quizgenerator = behat_util::get_data_generator()->get_plugin_generator('mod_quiz');
982
 
983
        $quizid = $DB->get_field('quiz', 'id', ['name' => $quizname], MUST_EXIST);
984
        $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
985
 
986
        $responses = $this->extract_responses_from_attempt_info($attemptinfo);
987
 
988
        $this->set_user($user);
989
 
990
        $attempts = quiz_get_user_attempts($quizid, $user->id, 'unfinished', true);
991
        $quizgenerator->submit_responses(key($attempts), $responses, true, false);
992
 
993
        $this->set_user();
994
    }
995
 
996
    /**
997
     * Finish an existing quiz attempt.
998
     *
999
     * @param string $username the username of the user that will attempt.
1000
     * @param string $quizname the name of the quiz the user will attempt.
1001
     * @Given /^user "([^"]*)" has finished an attempt at quiz "([^"]*)"$/
1002
     */
1003
    public function user_has_finished_an_attempt_at_quiz($username, $quizname) {
1004
        global $DB;
1005
 
1006
        $quizid = $DB->get_field('quiz', 'id', ['name' => $quizname], MUST_EXIST);
1007
        $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
1008
 
1009
        $this->set_user($user);
1010
 
1011
        $attempts = quiz_get_user_attempts($quizid, $user->id, 'unfinished', true);
1012
        $attemptobj = quiz_attempt::create(key($attempts));
1013
        $attemptobj->process_finish(time(), true);
1014
 
1015
        $this->set_user();
1016
    }
1017
 
1018
    /**
1019
     * Finish an existing quiz attempt.
1020
     *
1021
     * @param string $quizname the name of the quiz the user will attempt.
1022
     * @param string $username the username of the user that will attempt.
1023
     * @Given the attempt at :quizname by :username was never submitted
1024
     */
1025
    public function attempt_was_abandoned($quizname, $username) {
1026
        global $DB;
1027
 
1028
        $quizid = $DB->get_field('quiz', 'id', ['name' => $quizname], MUST_EXIST);
1029
        $user = $DB->get_record('user', ['username' => $username], '*', MUST_EXIST);
1030
 
1031
        $this->set_user($user);
1032
 
1033
        $attempt = quiz_get_user_attempt_unfinished($quizid, $user->id);
1034
        if (!$attempt) {
1035
            throw new coding_exception("No in-progress attempt found for $username and quiz $quizname.");
1036
        }
1037
        $attemptobj = quiz_attempt::create($attempt->id);
1038
        $attemptobj->process_abandon(time(), false);
1039
 
1040
        $this->set_user();
1041
    }
1042
 
1043
    /**
1044
     * Return a list of the exact named selectors for the component.
1045
     *
1046
     * @return behat_component_named_selector[]
1047
     */
1048
    public static function get_exact_named_selectors(): array {
1049
        return [
1050
            new behat_component_named_selector('Edit slot',
1051
            ["//li[contains(@class,'qtype')]//span[@class='slotnumber' and contains(., %locator%)]/.."])
1052
        ];
1053
    }
1054
}