MDL-48474 qtype_shortanswer: answers were not being trimmed.
authorTim Hunt <T.J.Hunt@open.ac.uk>
Thu, 8 Jan 2015 17:41:51 +0000 (17:41 +0000)
committerTim Hunt <T.J.Hunt@open.ac.uk>
Thu, 8 Jan 2015 17:41:51 +0000 (17:41 +0000)
This fix is based on Oleg Sychev's suggestion. Thanks.

question/type/shortanswer/questiontype.php
question/type/shortanswer/tests/questiontype_test.php

index fab260a..c98ec74 100644 (file)
@@ -78,6 +78,12 @@ class qtype_shortanswer extends question_type {
         $this->save_hints($question);
     }
 
+    protected function fill_answer_fields($answer, $questiondata, $key, $context) {
+        $answer = parent::fill_answer_fields($answer, $questiondata, $key, $context);
+        $answer->answer = trim($answer->answer);
+        return $answer;
+    }
+
     protected function initialise_question_instance(question_definition $question, $questiondata) {
         parent::initialise_question_instance($question, $questiondata);
         $this->initialise_question_answers($question, $questiondata);
index 91d2bcd..2bfa9a9 100644 (file)
@@ -141,4 +141,32 @@ class qtype_shortanswer_test extends advanced_testcase {
             }
         }
     }
+
+    public function test_question_saving_trims_answers() {
+        $this->resetAfterTest(true);
+        $this->setAdminUser();
+
+        $questiondata = test_question_maker::get_question_data('shortanswer');
+        $formdata = test_question_maker::get_question_form_data('shortanswer');
+
+        $generator = $this->getDataGenerator()->get_plugin_generator('core_question');
+        $cat = $generator->create_question_category(array());
+
+        $formdata->category = "{$cat->id},{$cat->contextid}";
+        $formdata->answer[0] = '   frog   ';
+        qtype_shortanswer_edit_form::mock_submit((array)$formdata);
+
+        $form = qtype_shortanswer_test_helper::get_question_editing_form($cat, $questiondata);
+
+        $this->assertTrue($form->is_validated());
+
+        $fromform = $form->get_data();
+
+        $returnedfromsave = $this->qtype->save_question($questiondata, $fromform);
+        $actualquestionsdata = question_load_questions(array($returnedfromsave->id));
+        $actualquestiondata = end($actualquestionsdata);
+
+        $firstsavedanswer = reset($questiondata->options->answers);
+        $this->assertEquals('frog', $firstsavedanswer->answer);
+    }
 }