on-demand release 4.5dev+
[moodle.git] / question / tests / generator / lib.php
blob07c13fdb76a78d2e40d6d293a366353e20173a87
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.
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 * Quiz module test data generator.
20 * @package core_question
21 * @copyright 2013 The Open University
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 use core_question\local\bank\question_version_status;
27 /**
28 * Class core_question_generator for generating question data.
30 * @package core_question
31 * @copyright 2013 The Open University
32 * @author 2021 Safat Shahin <safatshahin@catalyst-au.net>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 class core_question_generator extends component_generator_base {
37 /**
38 * @var number of created instances
40 protected $categorycount = 0;
42 /**
43 * Make the category count to zero.
45 public function reset() {
46 $this->categorycount = 0;
49 /**
50 * Create a new question category.
52 * @param array|stdClass $record
53 * @return stdClass question_categories record.
55 public function create_question_category($record = null) {
56 global $DB;
58 $this->categorycount ++;
60 $defaults = [
61 'name' => 'Test question category ' . $this->categorycount,
62 'info' => '',
63 'infoformat' => FORMAT_HTML,
64 'stamp' => make_unique_id_code(),
65 'sortorder' => 999,
66 'idnumber' => null
69 $record = $this->datagenerator->combine_defaults_and_record($defaults, $record);
71 if (!isset($record['contextid'])) {
72 if (isset($record['parent'])) {
73 $record['contextid'] = $DB->get_field('question_categories', 'contextid', ['id' => $record['parent']]);
74 } else {
75 $record['contextid'] = context_system::instance()->id;
78 if (!isset($record['parent'])) {
79 $record['parent'] = question_get_top_category($record['contextid'], true)->id;
81 $record['id'] = $DB->insert_record('question_categories', $record);
82 return (object) $record;
85 /**
86 * Create a new question. The question is initialised using one of the
87 * examples from the appropriate {@link question_test_helper} subclass.
88 * Then, any files you want to change from the value in the base example you
89 * can override using $overrides.
91 * @param string $qtype the question type to create an example of.
92 * @param string $which as for the corresponding argument of
93 * {@link question_test_helper::get_question_form_data}. null for the default one.
94 * @param array|stdClass $overrides any fields that should be different from the base example.
95 * @return stdClass the question data.
97 public function create_question($qtype, $which = null, $overrides = null) {
98 $question = new stdClass();
99 $question->qtype = $qtype;
100 $question->createdby = 0;
101 $question->idnumber = null;
102 $question->status = question_version_status::QUESTION_STATUS_READY;
104 return $this->update_question($question, $which, $overrides);
108 * Create a tag on a question.
110 * @param array $data with two elements ['questionid' => 123, 'tag' => 'mytag'].
112 public function create_question_tag(array $data): void {
113 $question = question_bank::load_question($data['questionid']);
114 core_tag_tag::add_item_tag('core_question', 'question', $question->id,
115 context::instance_by_id($question->contextid), $data['tag'], 0);
119 * Update an existing question.
121 * @param stdClass $question the question data to update.
122 * @param string $which as for the corresponding argument of
123 * {@link question_test_helper::get_question_form_data}. null for the default one.
124 * @param array|stdClass $overrides any fields that should be different from the base example.
125 * @return stdClass the question data, including version info and questionbankentryid
127 public function update_question($question, $which = null, $overrides = null) {
128 global $CFG, $DB;
129 require_once($CFG->dirroot . '/question/engine/tests/helpers.php');
130 $question = clone($question);
132 $qtype = $question->qtype;
134 $fromform = test_question_maker::get_question_form_data($qtype, $which);
135 $fromform = (object) $this->datagenerator->combine_defaults_and_record((array) $question, $fromform);
136 $fromform = (object) $this->datagenerator->combine_defaults_and_record((array) $fromform, $overrides);
137 $fromform->status = $fromform->status ?? $question->status;
139 $question = question_bank::get_qtype($qtype)->save_question($question, $fromform);
141 if ($overrides && (array_key_exists('createdby', $overrides) || array_key_exists('modifiedby', $overrides))) {
142 // Manually update the createdby and modifiedby because questiontypebase forces
143 // current user and some tests require a specific user.
144 if (array_key_exists('createdby', $overrides)) {
145 $question->createdby = $overrides['createdby'];
147 if (array_key_exists('modifiedby', $overrides)) {
148 $question->modifiedby = $overrides['modifiedby'];
150 $DB->update_record('question', $question);
152 $questionversion = $DB->get_record('question_versions', ['questionid' => $question->id], '*', MUST_EXIST);
153 $question->versionid = $questionversion->id;
154 $question->questionbankentryid = $questionversion->questionbankentryid;
155 $question->version = $questionversion->version;
156 $question->status = $questionversion->status;
158 return $question;
162 * Setup a course category, course, a question category, and 2 questions
163 * for testing.
165 * @param string $type The type of question category to create.
166 * @return array The created data objects
168 public function setup_course_and_questions($type = 'course') {
169 $datagenerator = $this->datagenerator;
170 $category = $datagenerator->create_category();
171 $course = $datagenerator->create_course([
172 'numsections' => 5,
173 'category' => $category->id
176 switch ($type) {
177 case 'category':
178 $context = context_coursecat::instance($category->id);
179 break;
181 case 'system':
182 $context = context_system::instance();
183 break;
185 default:
186 $context = context_course::instance($course->id);
187 break;
190 $qcat = $this->create_question_category(['contextid' => $context->id]);
192 $questions = [
193 $this->create_question('shortanswer', null, ['category' => $qcat->id]),
194 $this->create_question('shortanswer', null, ['category' => $qcat->id]),
197 return [$category, $course, $qcat, $questions];
201 * This method can construct what the post data would be to simulate a user submitting
202 * responses to a number of questions within a question usage.
204 * In the responses array, the array keys are the slot numbers for which a response will
205 * be submitted. You can submit a response to any number of questions within the usage.
206 * There is no need to do them all. The values are a string representation of the response.
207 * The exact meaning of that depends on the particular question type. These strings
208 * are passed to the un_summarise_response method of the question to decode.
210 * @param question_usage_by_activity $quba the question usage.
211 * @param array $responses the responses to submit, in the format described above.
212 * @param bool $checkbutton if simulate a click on the check button for each question, else simulate save.
213 * This should only be used with behaviours that have a check button.
214 * @return array that can be passed to methods like $quba->process_all_actions as simulated POST data.
216 public function get_simulated_post_data_for_questions_in_usage(
217 question_usage_by_activity $quba, array $responses, $checkbutton) {
218 $postdata = [];
220 foreach ($responses as $slot => $responsesummary) {
221 $postdata += $this->get_simulated_post_data_for_question_attempt(
222 $quba->get_question_attempt($slot), $responsesummary, $checkbutton);
225 return $postdata;
229 * This method can construct what the post data would be to simulate a user submitting
230 * responses to one particular question attempt.
232 * The $responsesummary is a string representation of the response to be submitted.
233 * The exact meaning of that depends on the particular question type. These strings
234 * are passed to the un_summarise_response method of the question to decode.
236 * @param question_attempt $qa the question attempt for which we are generating POST data.
237 * @param string $responsesummary a textual summary of the response, as described above.
238 * @param bool $checkbutton if simulate a click on the check button, else simulate save.
239 * This should only be used with behaviours that have a check button.
240 * @return array the simulated post data that can be passed to $quba->process_all_actions.
242 public function get_simulated_post_data_for_question_attempt(
243 question_attempt $qa, $responsesummary, $checkbutton) {
245 $question = $qa->get_question();
246 if (!$question instanceof question_with_responses) {
247 return [];
250 $postdata = [];
251 $postdata[$qa->get_control_field_name('sequencecheck')] = (string)$qa->get_sequence_check_count();
252 $postdata[$qa->get_flag_field_name()] = (string)(int)$qa->is_flagged();
254 $response = $question->un_summarise_response($responsesummary);
255 foreach ($response as $name => $value) {
256 $postdata[$qa->get_qt_field_name($name)] = (string)$value;
259 // TODO handle behaviour variables better than this.
260 if ($checkbutton) {
261 $postdata[$qa->get_behaviour_field_name('submit')] = 1;
264 return $postdata;