def test_should_contain_form_in_context(self): quiz_result = QuizResult( name='John Doe', quiz=self.quiz ) quiz_result.save() response = self.client.get(reverse('quiz', args=(quiz_result.id,))) self.assertEqual(200, response.status_code) self.assertIsNot(None, response.context['form'])
def test_should_redirect_home_if_quiz_is_taken(self): quiz_result = QuizResult( name='John Doe', quiz=self.quiz, completed=timezone.now() ) quiz_result.save() response = self.client.get(reverse('quiz', args=(quiz_result.id,))) self.assertEqual(302, response.status_code)
class QuizFormTestCase(TestCase): def setUp(self): self.quiz = Quiz( name='Test Quiz', slug='Test Quiz', description='' ) self.quiz.save() self.question_a = Question(question='Test Question A', correct_answer='Yes') self.question_a.save() self.question_b = Question(question='Test Question B', correct_answer='No') self.question_b.save() self.quiz.questions.add(self.question_a) self.quiz.questions.add(self.question_b) self.quiz_result = QuizResult(name='J Doe', quiz=self.quiz) self.quiz_result.save() self.data = {} for answer in self.quiz_result.answers.all(): question_text = answer.question.question self.data['question_{0}'.format(answer.id)] = 'Yes' def test_questions_are_populated_and_required(self): quiz_form = QuizForm(blank_answers=self.quiz_result.answers.all(), data=self.data) self.assertEqual(2, len(quiz_form.fields)) for key in quiz_form.fields.iterkeys(): self.assertTrue(quiz_form.fields[key].required) def test_questions_marked_as_answered_on_save(self): quiz_form = QuizForm(blank_answers=self.quiz_result.answers.all(), data=self.data) quiz_form.is_valid() quiz_form.save(self.quiz_result) # Note: an unanswered question is represented by None answers = self.quiz_result.answers.all() for answer in answers: self.assertNotEqual(None, answer.correct) def test_quiz_completed_datetime_set_on_save(self): quiz_form = QuizForm(blank_answers=self.quiz_result.answers.all(), data=self.data) quiz_form.is_valid() self.assertEqual(None, self.quiz_result.completed) quiz_form.save(self.quiz_result) self.assertNotEqual(None, self.quiz_result.completed)
def home_view(request): if request.user.is_authenticated: #Check if form is submitted if request.method == 'POST': answers = [] quizId = request.POST.get('quiz', None) quizName = request.POST.get('quizName', None) for key in request.POST: if 'question' in key: questionId = key.split('_')[1] answer = request.POST[key] gameAnswer = GameAnswer(questionId, answer) quizAnswer = QuizAnswer(questionId=questionId, questionAnswer=answer) quizAnswer.save() answers.append(gameAnswer.__dict__) response = requests.post('http://127.0.0.1:8000/api/answers/' + quizId, json=answers) quizResult = GameResult(**response.json()) userQuizResult = QuizResult( quizName=quizName, correctAnswers=quizResult.correct_answers, userName=request.user) userQuizResult.save() return render(request, 'result.html', {'result': quizResult}) else: response = requests.get('http://127.0.0.1:8000/api/quiz') quiz = GameQuiz(**response.json()) return render(request, 'home.html', { 'user': request.user, 'quiz': quiz }) else: return redirect('login')
def submit(request): if request.user.is_authenticated(): # if user is logged in https://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs user = request.user if request.method == 'POST': # and if request is a POST quiz = Quiz.objects.get(id=int(request.POST.get('quizID'))) try: user_quizresult = QuizResult.objects.get(user=user) except Exception: user_quizresult = None if user_quizresult: quizData = str(request.POST.get('quizString')) user_quizresult.collectQuizData(quizData) else: user_quizresult = QuizResult.create(quiz, user) # init a null quiz result quizData = str(request.POST.get('quizString')) user_quizresult.collectQuizData(quizData) return redirect('/quiz/complete') else: # else user needs to log in return HttpResponseRedirect('/login') # redirect to some result page to show the "result"
def tc_run_final_view(request, tc_id): tc = get_object_or_404(TaskCollection, pk=tc_id) response = HttpResponse() if "tc_task_id" not in request.session: response.write("<p>You haven't even started the quiz yet.</p>") return response if "tc_id" in request.session: if int(tc_id) != request.session["tc_id"]: response.write( "<p>You can't switch task collections on your own.</p>") return response tc_task_id = request.session["tc_task_id"] if tc_task_id < tc.number_of_tasks() - 1: response.write("<p>You're not done with the quiz yet.</p>") return response log = "" if "log" in request.session: log = request.session["log"] log += "Show final page." request.session.clear() current_date = datetime.now() date_iso8601 = current_date.isoformat(" ") hash_string = compute_hash(log, date_iso8601) quiz_result = QuizResult() quiz_result.date = current_date quiz_result.hash = hash_string quiz_result.log = log quiz_result.save() context_dict = dict(tc=tc) context_dict["hash"] = hash_string context = Context(context_dict) return render(request, 'tasks/tc_run_final.html', context)
def setUp(self): self.quiz = Quiz( name='Test Quiz', slug='Test Quiz', description='' ) self.quiz.save() self.question_a = Question(question='Test Question A', correct_answer='Yes') self.question_a.save() self.question_b = Question(question='Test Question B', correct_answer='No') self.question_b.save() self.quiz.questions.add(self.question_a) self.quiz.questions.add(self.question_b) self.quiz_result = QuizResult(name='J Doe', quiz=self.quiz) self.quiz_result.save() self.data = {} for answer in self.quiz_result.answers.all(): question_text = answer.question.question self.data['question_{0}'.format(answer.id)] = 'Yes'
def post(self, request, quiz_id: str, question_num: str, *args, **kwargs) -> HttpResponseRedirect: def check_correct() -> Tuple[int, bool]: obj = self.get_object() answers = map(int, request.POST.getlist('answers', [])) corrects = Answer.objects.filter( question=obj, is_correct=True).values_list('id', flat=True) return obj.id, set(answers) == set(corrects) def save_result_to_session(question_id: int, result: bool) -> None: if 'answers' not in request.session: request.session['answers'] = {} request.session['answers'][question_id] = result request.session.save() # keep in mind situation when admin changing question save_result_to_session(*check_correct()) question_num = int(question_num) if Question.objects.filter(quiz_id=quiz_id).count() == question_num: # For production I'll create my own session storage (based on default) for working with answers. # Next line must be encapsulated into session object. answers = { int(key): value for key, value in request.session['answers'].items() } quiz_result = QuizResult.create_from_answers( quiz_id=int(quiz_id), user_id=request.user.id, answers=answers) url = quiz_result.get_absolute_url() else: url = reverse('question', kwargs={ 'quiz_id': quiz_id, 'question_num': question_num + 1 }) return HttpResponseRedirect( url ) # yes, I know about unnecessary request, but it's just for demo
def tc_run_final_view(request, tc_id): tc = get_object_or_404(TaskCollection, pk=tc_id) response = HttpResponse() if "tc_task_id" not in request.session: response.write("<p>You haven't even started the quiz yet.</p>") return response if "tc_id" in request.session: if int(tc_id) != request.session["tc_id"]: response.write("<p>You can't switch task collections on your own.</p>") return response tc_task_id = request.session["tc_task_id"] if tc_task_id < tc.number_of_tasks() - 1: response.write("<p>You're not done with the quiz yet.</p>") return response log = "" if "log" in request.session: log = request.session["log"] log += "Show final page." request.session.clear() current_date = datetime.now() date_iso8601 = current_date.isoformat(" ") hash_string = compute_hash(log, date_iso8601) quiz_result = QuizResult() quiz_result.date = current_date quiz_result.hash = hash_string quiz_result.log = log quiz_result.save() context_dict = dict(tc=tc) context_dict["hash"] = hash_string context = Context(context_dict) return render(request, 'tasks/tc_run_final.html', context)
def create(self, validated_data): # user = CurrentUserDefault() return QuizResult(**validated_data)