Exemple #1
0
 def test_select(
     self,
     user: settings.AUTH_USER_MODEL,
     survey: Survey,
     department: Department,
     question: Question,
 ):
     department.user_set.add(user)
     [question.option_set.add(OptionFactory()) for _ in range(3)]
     question.qtype = "SELECT"
     first_option = question.option_set.all()[0]
     form = FlexiForm(
         data={
             "option": str(first_option.id),
             "qid": str(question.id),
         },
         survey=survey,
         department=department,
         question=question,
     )
     assert form.is_valid()
     str(form.question.option_set.first().id)
     form.save()
     ans = Answer.objects.filter(department__pk=department.pk).first()
     opts = ans.options.all()
     assert len(opts) == 1
     assert form.as_p().count('option') >= 3
Exemple #2
0
 def test_multiple_choice(
     self,
     user: settings.AUTH_USER_MODEL,
     survey: Survey,
     department: Department,
     question: Question,
 ):
     department.user_set.add(user)
     [question.option_set.add(OptionFactory()) for _ in range(3)]
     question.qtype = "MULTICHOICE"
     first_option = question.option_set.all()[0]
     second_option = question.option_set.all()[1]
     form = FlexiForm(
         data={
             "option": [str(first_option.id),
                        str(second_option.id)],
             "qid": str(question.id),
         },
         survey=survey,
         department=department,
         question=question,
     )
     assert form.is_valid()
     assert form.cleaned_data["option"] == [
         str(first_option.id),
         str(second_option.id),
     ]
     form.save()
     ans = Answer.objects.filter(department__pk=department.pk).first()
     opts = ans.options.all()
     assert len(opts) == 2
     assert form.as_p().count('checkbox') >= 3
Exemple #3
0
 def test_email_compliant(
     self,
     user: settings.AUTH_USER_MODEL,
     survey: Survey,
     department: Department,
     question: Question,
 ):
     department.user_set.add(user)
     question.qtype = "EMAIL"
     TEST_TEXT = '*****@*****.**'
     form = FlexiForm(
         data={
             "option": TEST_TEXT,
             "qid": str(question.id),
         },
         survey=survey,
         department=department,
         question=question,
     )
     assert form.is_valid()
     form.save()
     ans = Answer.objects.filter(department__pk=department.pk).first()
     opts = ans.options.all()
     assert len(opts) == 0
     assert ans.value.text == TEST_TEXT
Exemple #4
0
    def test_single_choice(
        self,
        user: settings.AUTH_USER_MODEL,
        survey: Survey,
        department: Department,
        question: Question,
    ):

        department.user_set.add(user)
        [question.option_set.add(OptionFactory()) for i in range(3)]
        question.qtype = "SINGLECHOICE"
        first_option = question.option_set.first()
        form = FlexiForm(
            data={
                "option": str(first_option.id),
                "qid": str(question.id)
            },
            survey=survey,
            department=department,
            question=question,
        )
        assert form.is_valid()
        assert form.cleaned_data["option"] == str(
            form.question.option_set.first().id)
        form.save()
        ans = Answer.objects.filter(department__pk=department.pk).first()
        opt = ans.options.first()
        assert opt.pk == first_option.pk
        assert form.as_p().count('radio') >= 3
Exemple #5
0
 def test_essay(
     self,
     user: settings.AUTH_USER_MODEL,
     survey: Survey,
     department: Department,
     question: Question,
 ):
     department.user_set.add(user)
     question.qtype = "ESSAY"
     TEST_TEXT = """something here
     and there"""
     form = FlexiForm(
         data={
             "option": TEST_TEXT,
             "qid": str(question.id),
         },
         survey=survey,
         department=department,
         question=question,
     )
     assert form.is_valid()
     form.save()
     ans = Answer.objects.filter(department__pk=department.pk).first()
     opts = ans.options.all()
     assert len(opts) == 0
     assert ans.value.text == TEST_TEXT
Exemple #6
0
 def test_email_non_compliant(
     self,
     user: settings.AUTH_USER_MODEL,
     survey: Survey,
     department: Department,
     question: Question,
 ):
     department.user_set.add(user)
     question.qtype = "EMAIL"
     TEST_TEXT = 'gmail.com'
     form = FlexiForm(
         data={
             "option": TEST_TEXT,
             "qid": str(question.id),
         },
         survey=survey,
         department=department,
         question=question,
     )
     assert not form.is_valid()
Exemple #7
0
def create_question(content: str, author_id: int, id: int = 1):
    # fmt: off
    question = Question(id=id, content=content, author_id=author_id)
    # fmt: on
    question.save()
    return question
Exemple #8
0
def edit(request, survey_id):
    s = get_object_or_404(Survey, pk=survey_id)
    # only admins and survey owner can view this page
    if request.user.is_staff or (request.user.is_authenticated()
                                 and s.owner == request.user):
        if request.method == "POST":
            # editing is only allowed when survey status is 'ACTIVE'
            if s.status == s.STATUS_ACTIVE:
                errors = {}
                for k, v in request.POST.items():
                    if k.startswith("surveyTitle"):
                        s.title = v
                        s.save()
                    elif k.startswith("questionName"):
                        k, pk = k.split('-')
                        q = s.question_set.get(pk=pk)
                        q.question = v
                        q.save()
                    elif k.startswith("questionType"):
                        k, pk = k.split('-')
                        q = s.question_set.get(pk=pk)
                        q.type = int(v)
                        q.save()
                    elif k.startswith("choice"):
                        k, pk = k.split('-')
                        c = Choice.objects.get(pk=pk)
                        if v and v != "Add new choice":
                            c.choice = v
                            c.save()
                        else:
                            c.delete()
                    elif k.startswith("newChoice"):
                        k, pk = k.split('-')
                        if v and v != "Add new choice" and v != "":
                            q = s.question_set.get(pk=pk)
                            c = Choice()
                            c.question = q
                            c.choice = v
                            c.votes = 0
                            c.save()
                    elif k == "newQuestion" and v and v != "Enter a new question":
                        q = Question()
                        q.survey = s
                        q.question = v
                        if request.POST["newQuestionType"]:
                            q.type = int(request.POST["newQuestionType"])
                        else:
                            q.type = 1
                        q.save()
                if 'publish' in request.POST:
                    if s.question_set.all().count() == 0:
                        errors[
                            'publishError'] = "You cannot publish an empty survey. Create some questions first."
                        return render_to_response(
                            'surveys/edit/edit.html', {
                                'survey':
                                s,
                                'today':
                                datetime.datetime.now(),
                                'tomorrow':
                                datetime.datetime.now() +
                                datetime.timedelta(days=1),
                                'errors':
                                errors
                            },
                            context_instance=RequestContext(request))
                    if 'resultDisplay' in request.POST and 'endtime' in request.POST:
                        if not s.publish(
                                resultDisplay=request.POST["resultDisplay"],
                                endtime=dateutil.parser.parse(
                                    request.POST["endtime"], dayfirst=True)):
                            return HttpResponseRedirect(
                                reverse('surveys.views.edit', args=(s.id, )))
            # actions for published surveys
            elif s.status == s.STATUS_PUBLISHED:
                if "end" in request.POST:
                    ACTION_CONFIRM = 0
                    ACTION_END = 1
                    if "confirm" in request.POST:
                        s.end()
                        return render_to_response(
                            'surveys/edit/end.html', {
                                'survey': s,
                                'action': ACTION_END
                            },
                            context_instance=RequestContext(request))
                    if "negative" in request.POST:
                        return HttpResponseRedirect(
                            reverse('surveys.views.edit', args=(s.id, )))
                    else:
                        return render_to_response(
                            'surveys/edit/end.html', {
                                'survey': s,
                                'action': ACTION_CONFIRM
                            },
                            context_instance=RequestContext(request))
                if "unpublish" in request.POST:
                    if request.user.is_staff:
                        s.status = s.STATUS_ACTIVE
                        s.save()
            elif s.status == s.STATUS_INACTIVE:
                if "undelete" in request.POST:
                    if request.user.is_staff:
                        s.status = s.STATUS_ACTIVE
                        s.save()
            if not s.status == s.STATUS_INACTIVE:
                if "delete" in request.POST:
                    if request.user.is_staff:
                        s.status = s.STATUS_INACTIVE
                        s.save()

            if "ban" in request.POST:
                if request.user.is_staff:
                    s.owner.is_active = False
                    s.owner.save()

            elif "unban" in request.POST:
                if request.user.is_staff:
                    s.owner.is_active = True
                    s.owner.save()

            return HttpResponseRedirect(
                reverse('surveys.views.edit', args=(s.id, )))
        return render_to_response(
            'surveys/edit/edit.html', {
                'survey': s,
                'today': datetime.datetime.now(),
                'tomorrow':
                datetime.datetime.now() + datetime.timedelta(days=1)
            },
            context_instance=RequestContext(request))
    else:
        return render_to_response('surveys/edit/error.html', {
            'survey': s,
        })
Exemple #9
0
def edit(request, survey_id):
    s = get_object_or_404(Survey, pk=survey_id)
    # only admins and survey owner can view this page
    if request.user.is_staff or (request.user.is_authenticated() and s.owner == request.user):
        if request.method == "POST":
            # editing is only allowed when survey status is 'ACTIVE'
            if s.status == s.STATUS_ACTIVE:
                errors = {}
                for k, v in request.POST.items():
                    if k.startswith("surveyTitle"):
                        s.title = v
                        s.save()
                    elif k.startswith("questionName"):
                        k, pk = k.split('-')
                        q = s.question_set.get(pk=pk)
                        q.question = v
                        q.save()
                    elif k.startswith("questionType"):
                        k, pk = k.split('-')
                        q = s.question_set.get(pk=pk)
                        q.type = int(v)
                        q.save()
                    elif k.startswith("choice"):
                        k, pk = k.split('-')
                        c = Choice.objects.get(pk=pk)
                        if v and v != "Add new choice":
                            c.choice = v
                            c.save()
                        else:
                            c.delete()
                    elif k.startswith("newChoice"):
                        k, pk = k.split('-')
                        if v and v != "Add new choice" and v != "":
                            q = s.question_set.get(pk=pk)
                            c = Choice()
                            c.question = q
                            c.choice = v
                            c.votes = 0
                            c.save()
                    elif k == "newQuestion" and v and v != "Enter a new question":
                        q = Question()
                        q.survey = s
                        q.question = v
                        if request.POST["newQuestionType"]:
                            q.type = int(request.POST["newQuestionType"])
                        else:
                            q.type = 1
                        q.save()
                if 'publish' in request.POST:
                    if s.question_set.all().count() == 0:
                        errors['publishError'] = "You cannot publish an empty survey. Create some questions first."
                        return render_to_response('surveys/edit/edit.html', {'survey': s, 'today':datetime.datetime.now(), 'tomorrow': datetime.datetime.now() + datetime.timedelta(days=1), 'errors': errors}, context_instance=RequestContext(request))
                    if 'resultDisplay' in request.POST and 'endtime' in request.POST:
                        if not s.publish(resultDisplay=request.POST["resultDisplay"], endtime=dateutil.parser.parse(request.POST["endtime"], dayfirst=True)):
                            return HttpResponseRedirect(reverse('surveys.views.edit', args=(s.id,)))
            # actions for published surveys
            elif s.status == s.STATUS_PUBLISHED:
                if "end" in request.POST:
                    ACTION_CONFIRM = 0
                    ACTION_END = 1
                    if "confirm" in request.POST:
                        s.end()
                        return render_to_response('surveys/edit/end.html', {'survey': s, 'action': ACTION_END}, context_instance=RequestContext(request))
                    if "negative" in request.POST:
                        return HttpResponseRedirect(reverse('surveys.views.edit', args=(s.id,)))
                    else:
                        return render_to_response('surveys/edit/end.html', {'survey': s, 'action': ACTION_CONFIRM}, context_instance=RequestContext(request))
                if "unpublish" in request.POST:
                    if request.user.is_staff:
                        s.status = s.STATUS_ACTIVE
                        s.save()
            elif s.status == s.STATUS_INACTIVE:
                if "undelete" in request.POST:
                    if request.user.is_staff:
                        s.status = s.STATUS_ACTIVE
                        s.save()
            if not s.status == s.STATUS_INACTIVE:
                if "delete" in request.POST:
                    if request.user.is_staff:
                        s.status = s.STATUS_INACTIVE
                        s.save()

            if "ban" in request.POST:
                if request.user.is_staff:
                    s.owner.is_active = False
                    s.owner.save()

            elif "unban" in request.POST:
                if request.user.is_staff:
                    s.owner.is_active = True
                    s.owner.save()


            return HttpResponseRedirect(reverse('surveys.views.edit', args=(s.id,)))
        return render_to_response('surveys/edit/edit.html', {'survey': s, 'today':datetime.datetime.now(), 'tomorrow': datetime.datetime.now() + datetime.timedelta(days=1)}, context_instance=RequestContext(request))
    else:
        return render_to_response('surveys/edit/error.html', {'survey': s,})
Exemple #10
0
def new_question(request):
    body = json.loads(request.body)
    question = Question(content=body["content"])
    question.save()
    return JsonResponse({"data": body})