コード例 #1
0
    def test_show_join_banner(self):
        template_settings = deepcopy(settings.TEMPLATES)
        template_settings[0]['DIRS'] = [
            join(settings.PROJECT_ROOT, 'templates', 'springster')
        ]

        with self.settings(TEMPLATES=template_settings):
            molo_form_page = MoloFormPage(
                title='from title',
                slug='form-slug',
                homepage_introduction='Introduction to Test Form ...',
                thank_you_text='Thank you for taking the Test Form',
                allow_anonymous_submissions=False)
            self.form_index.add_child(instance=molo_form_page)

            molo_form_page2 = MoloFormPage(
                title='form title',
                slug='another-form-slug',
                homepage_introduction='Introduction to Test Form ...',
                thank_you_text='Thank you for taking the Test Form',
                allow_anonymous_submissions=True)

            self.form_index.add_child(instance=molo_form_page2)

            MoloFormField.objects.create(page=molo_form_page,
                                         sort_order=1,
                                         label='Your favourite animal',
                                         field_type='singleline',
                                         required=True)
            MoloFormField.objects.create(page=molo_form_page2,
                                         sort_order=1,
                                         label='Your birthday month',
                                         field_type='singleline',
                                         required=True)
            molo_form_page.save_revision().publish()
            molo_form_page2.save_revision().publish()
            setting = GemSettings.for_site(self.main.get_site())
            self.assertFalse(setting.show_join_banner)
            response = self.client.get('%s?next=%s' %
                                       (reverse('molo.profiles:auth_logout'),
                                        reverse('molo.profiles:auth_login')))
            response = self.client.get('/')
            self.assertNotContains(response, self.banner_message)
            setting.show_join_banner = True
            setting.save()

            self.assertTrue(
                GemSettings.for_site(self.main.get_site()).show_join_banner)
            self.assertTrue(
                SiteSettings.for_site(
                    self.main.get_site()).enable_tag_navigation)
            response = self.client.get('/')
            self.assertContains(response, self.banner_message)

            # test that the join banner only shows up once
            soup = BeautifulSoup(response.content, 'html.parser')
            self.assertEqual(soup.get_text().count(self.banner_message), 1)
コード例 #2
0
class SkipLogicPaginatorPageBreak(TestCase, MoloTestCaseMixin):
    def setUp(self):
        self.mk_main()
        self.form = MoloFormPage(
            title='Test Form',
            slug='test-form',
        )
        self.section_index.add_child(instance=self.form)
        self.form.save_revision().publish()
        self.first_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=1,
            label='Your other favourite animal',
            field_type='singleline',
            required=True,
            page_break=True,
        )
        self.second_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=2,
            label='Your favourite animal',
            field_type='singleline',
            required=True,
            page_break=True,
        )
        self.last_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=3,
            label='Your least favourite animal',
            field_type='singleline',
            required=True)
        self.paginator = SkipLogicPaginator(self.form.get_form_fields())

    def test_correct_num_pages(self):
        self.assertEqual(self.paginator.num_pages, 3)

    def test_page_breaks_correct(self):
        self.assertEqual(self.paginator.page_breaks, [0, 1, 2, 3])

    def test_first_page_correct(self):
        self.assertEqual(
            self.paginator.page(1).object_list,
            [self.first_field],
        )

    def test_middle_page_correct(self):
        self.assertEqual(
            self.paginator.page(2).object_list,
            [self.second_field],
        )

    def test_last_page_correct(self):
        last_page = self.paginator.page(3)
        self.assertEqual(last_page.object_list, [self.last_field])
        self.assertFalse(last_page.has_next())
コード例 #3
0
class TestSkipLogicBlock(TestCase, MoloTestCaseMixin):
    def setUp(self):
        self.mk_main()
        self.form = MoloFormPage(
            title='Test Form',
            slug='test-form',
        )
        self.section_index.add_child(instance=self.form)
        self.form.save_revision().publish()

    def test_form_raises_error_if_no_object(self):
        block = SkipLogicBlock()
        data = skip_logic_block_data(
            'next form',
            SkipState.FORM,
            form=None,
        )
        with self.assertRaises(ValidationError):
            block.clean(data)

    def test_form_passes_with_object(self):
        block = SkipLogicBlock()
        data = skip_logic_block_data(
            'next form',
            SkipState.FORM,
            form=self.form.id,
        )
        cleaned_data = block.clean(data)
        self.assertEqual(cleaned_data['skip_logic'], SkipState.FORM)
        self.assertEqual(cleaned_data['form'], self.form)

    def test_question_raises_error_if_no_object(self):
        block = SkipLogicBlock()
        data = skip_logic_block_data(
            'a question',
            SkipState.QUESTION,
            question=None,
        )
        with self.assertRaises(ValidationError):
            block.clean(data)

    def test_question_passes_with_object(self):
        block = SkipLogicBlock()
        data = skip_logic_block_data(
            'a question',
            SkipState.QUESTION,
            question=1,
        )
        cleaned_data = block.clean(data)
        self.assertEqual(cleaned_data['skip_logic'], SkipState.QUESTION)
        self.assertEqual(cleaned_data['question'], 1)
コード例 #4
0
    def create_molo_form_field(self, field_type):
        form = MoloFormPage(
            title='Test Form',
            introduction='Introduction to Test Form ...',
        )
        FormsIndexPage.objects.first().add_child(instance=form)
        form.save_revision().publish()

        return MoloFormField.objects.create(
            page=form,
            label="When is your birthday",
            field_type=field_type,
            admin_label="birthday",
        )
コード例 #5
0
    def create_molo_form_page(self, parent, **kwargs):
        molo_form_page = MoloFormPage(
            title='Test Form',
            slug='test-form',
            introduction='Introduction to Test Form ...',
            thank_you_text='Thank you for taking the Test Form',
            submit_text='form submission text',
            **kwargs)

        parent.add_child(instance=molo_form_page)
        molo_form_page.save_revision().publish()
        molo_form_field = MoloFormField.objects.create(
            page=molo_form_page,
            sort_order=1,
            label='Your favourite animal',
            field_type='singleline',
            required=True)
        return molo_form_page, molo_form_field
コード例 #6
0
ファイル: base.py プロジェクト: praekeltfoundation/molo.forms
def create_molo_form_page(
        parent,
        title="Test Form",
        slug='test-form',
        thank_you_text='Thank you for taking the Test Form',
        homepage_introduction='Shorter homepage introduction',
        **kwargs):
    molo_form_page = MoloFormPage(title=title,
                                  slug=slug,
                                  introduction='Introduction to Test Form ...',
                                  thank_you_text=thank_you_text,
                                  submit_text='form submission text',
                                  homepage_introduction=homepage_introduction,
                                  **kwargs)

    parent.add_child(instance=molo_form_page)
    molo_form_page.save_revision().publish()

    return molo_form_page
コード例 #7
0
ファイル: base.py プロジェクト: praekeltfoundation/molo-gem
    def mk_reaction_question(self, parent, article, **kwargs):
        data = {}
        data.update({
            'introduction': 'Test Question',
        })
        data.update(kwargs)
        data.update({
            'slug': generate_slug(data['title'])
        })
        form = MoloFormPage(**data)
        parent.add_child(instance=form)
        form.save_revision().publish()
        field = MoloFormField(
            choices='yes,maybe,no', success_message='well done')
        form.add_child(instance=field)
        field.save_revision().publish()

        ArticlePageForms.objects.create(
            reaction_question=form, page=article)
        return form
コード例 #8
0
    def setUp(self):
        super().setUp()

        # Create content
        section_index = SectionIndexPage.objects.child_of(self.main).first()
        section = self.mk_section(section_index, title='Section')
        article = self.mk_article(
            parent=section, title='Article')

        # Note: this 'site' attr is the django site, not the wagtail one
        MoloComment.objects.create(
            content_type=self.content_type,
            site=Site.objects.get_current(),
            object_pk=article.pk,
            user=self.user,
            comment="Here's a comment",
            submit_date=timezone.now())

        form = MoloFormPage(
            title='Form',
            slug='form',
        )
        section_index.add_child(instance=form)
        form.save_revision().publish()
        MoloFormSubmission.objects.create(
            form_data='{"checkbox-question": ["option 1", "option 2"]}',
            user=self.user,
            page_id=form.pk
        )

        self.profile = self.user.profile
        sq_index = SecurityQuestionIndexPage.objects.child_of(
            self.main).first()
        sec_q = SecurityQuestion(title='Sec Question')
        sq_index.add_child(instance=sec_q)
        sec_q.save_revision().publish()
        SecurityAnswer.objects.create(
            user=self.profile, question=sec_q, answer="Sec Answer")
コード例 #9
0
class TestSkipLogicMixin(TestCase, MoloTestCaseMixin):
    def setUp(self):
        self.mk_main()
        self.field_choices = ['old', 'this', 'is']
        self.form = MoloFormPage(
            title='Test Form',
            slug='test-form',
        )
        self.section_index.add_child(instance=self.form)
        self.form.save_revision().publish()
        self.choice_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=1,
            label='Your favourite animal',
            field_type='dropdown',
            skip_logic=skip_logic_data(self.field_choices),
            required=True)
        self.normal_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=2,
            label='Your other favourite animal',
            field_type='singleline',
            required=True)
        self.positive_number_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=3,
            label='How old are you',
            field_type='positive_number',
            required=True)

    def test_form_options_512_limit_overriden(self):
        field_choices = [
            'My favourite animal is a dog, because they bark',
            'My favourite animal is a cat, because they meuow',
            'My favourite animal is a bird, because they fly',
            'My favourite animal is a lion, because that roar',
            'My favourite animal is a hamster, because they have tiny legs',
            'My favourite animal is a tiger, because they have stripes',
            'My favourite animal is a frog, because they go crickit',
            'My favourite animal is a fish, because they have nice eyes',
            'My favourite animal is a chicken, because they cannot fly',
            'My favourite animal is a duck, because they keep it down',
            'My favourite animal is a wolf, because they howl',
            'My favourite animal is a chamelion, because they fit in',
        ]
        choice_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=1,
            label='Your favourite animal',
            field_type='dropdown',
            skip_logic=skip_logic_data(field_choices),
            required=True)
        self.assertTrue(len(choice_field.choices) > 512)

    def test_choices_updated_from_streamfield_on_save(self):
        self.assertEqual(','.join(self.field_choices),
                         self.choice_field.choices)

        new_choices = ['this', 'is', 'new']
        self.choice_field.skip_logic = skip_logic_data(new_choices)
        self.choice_field.save()

        self.assertEqual(','.join(new_choices), self.choice_field.choices)

    def test_normal_field_is_not_skippable(self):
        self.assertFalse(self.normal_field.has_skipping)

    def test_positive_number_field_is_not_skippable(self):
        self.assertFalse(self.positive_number_field.has_skipping)

    def test_only_next_doesnt_skip(self):
        self.assertFalse(self.choice_field.has_skipping)

    def test_other_logic_does_skip(self):
        self.choice_field.skip_logic = skip_logic_data(['choice'], ['end'])
        self.choice_field.save()
        self.assertTrue(self.choice_field.has_skipping)
コード例 #10
0
    def handle(self, *args, **options):
        for main in Main.objects.all():
            print(
                "*" * 10,
                "Migrating Surveys in",
                main,
                "*" * 10,
            )
            surveys_index = SurveysIndexPage.objects.child_of(main).first()
            forms_index = FormsIndexPage.objects.descendant_of(main).filter(
                slug='surveys-indexpage').first()
            surveys_tc = TermsAndConditionsIndexPage.objects.child_of(
                surveys_index).first()

            # Copy the Survey Ts&Cs to Forms
            if surveys_tc:
                forms_tc = FormsTermsAndConditionsIndexPage.objects.filter(
                    slug='terms-conditions-indexpage').child_of(
                        forms_index).first()
                forms_index.add_child(instance=forms_tc)
                forms_tc.save_revision().publish()
                for footerpage in FooterPage.objects.child_of(surveys_tc):
                    footer_dict = {}
                    exclude = (
                        '_state',
                        'id',
                        'path',
                        'numchild',
                        'page_ptr_id',
                        'content_type_id',
                        'articlepage_ptr_id',
                        '_language_cache',
                    )
                    for item in footerpage.__dict__.items():
                        if item[0] not in exclude:
                            footer_dict[item[0]] = item[1]

                    footer_page = FooterPage(**footer_dict)
                    forms_tc.add_child(instance=footer_page)
                    if footerpage.status_string == 'draft' \
                            or footerpage.status_string == 'expired':
                        footer_page.specific.unpublish()
                    else:
                        footer_page.save_revision().publish()
            print("Copying of Survey Ts&Cs is Done")

            # Migrate Survey Page to Form Page
            translated_survey = {}
            for survey in MoloSurveyPage.objects.descendant_of(
                    surveys_index).exact_type(MoloSurveyPage):
                if survey.language.is_main_language and\
                     survey.translated_pages.first():
                    translated_survey[survey.slug] = \
                        survey.translated_pages.first().slug

                survey_dict = {}
                exclude = ('_state', 'id', 'path', 'numchild', 'page_ptr_id',
                           'content_type_id', 'landing_page_template',
                           '_language_cache')
                for item in survey.__dict__.items():
                    if item[0] not in exclude:
                        survey_dict[item[0]] = item[1]

                survey_id = survey.id
                survey_dict['slug'] = "form-" + survey_dict['slug']
                survey_dict['display_form_directly'] = survey_dict[
                    'display_survey_directly']
                del survey_dict['display_survey_directly']

                form = MoloFormPage(**survey_dict)
                forms_index.add_child(instance=form)
                if survey.status_string == 'draft'\
                        or survey.status_string == 'expired':
                    form.specific.unpublish()
                else:
                    form.save_revision().publish()

                if survey.terms_and_conditions.first():
                    form_tc = FooterPage.objects.child_of(forms_tc).filter(
                        title=survey.terms_and_conditions.first(
                        ).terms_and_conditions.title)
                    survey.terms_and_conditions.first().terms_and_conditions
                    FormTermsConditions.objects.create(
                        page=form, terms_and_conditions=form_tc.first())

                for form_field in MoloSurveyFormField.objects.filter(
                        page_id=survey_id):
                    form_field_dict = {}
                    for item in form_field.__dict__.items():
                        form_field_dict[item[0]] = item[1]
                    form_field_dict['page_id'] = form.id
                    del form_field_dict['_state']
                    del form_field_dict['id']

                    MoloFormField.objects.create(**form_field_dict)

                for submission in MoloSurveySubmission.objects.filter(
                        page_id=survey_id):
                    submission_dict = {}
                    for item in submission.__dict__.items():
                        submission_dict[item[0]] = item[1]

                    del submission_dict['_state']
                    del submission_dict['id']
                    submission_dict['submit_time'] = submission_dict[
                        'created_at']
                    del submission_dict['created_at']
                    submission_dict['page_id'] = form.id
                    form_submission = MoloFormSubmission.objects.create(
                        **submission_dict)
                    form_submission.submit_time =\
                        submission_dict['submit_time']
                    form_submission.save()

            for key in translated_survey:
                main_form = MoloFormPage.objects.descendant_of(
                    forms_index).get(slug="form-%s" % key).specific
                translated_form = MoloFormPage.objects.descendant_of(
                    forms_index).get(slug="form-%s" %
                                     translated_survey[key]).specific
                main_form.translated_pages.add(translated_form)
                translated_form.translated_pages.add(main_form)
            print("Migration of SurveyPage is Done")

            # Migrate Personalisable Survey to Form
            translated_survey = {}
            for personalisable_survey in \
                PersonalisableSurvey.objects.descendant_of(
                    surveys_index).exact_type(PersonalisableSurvey):
                if personalisable_survey.language.is_main_language and \
                     personalisable_survey.translated_pages.first():
                    translated_survey[personalisable_survey.slug] = \
                        personalisable_survey.translated_pages.first().slug

                personalisable_survey_dict = {}
                exclude = ('_state', 'id', 'content_type_id',
                           'molosurveypage_ptr_id', 'numchild',
                           'landing_page_template', 'page_ptr_id',
                           '_language_cache')
                for item in personalisable_survey.__dict__.items():
                    if item[0] not in exclude:
                        personalisable_survey_dict[item[0]] = item[1]

                personalisable_survey_id = personalisable_survey.id
                personalisable_survey_dict['slug'] = \
                    "form-" + personalisable_survey_dict['slug']
                personalisable_survey_dict['display_form_directly'] \
                    = personalisable_survey_dict[
                        'display_survey_directly']
                del personalisable_survey_dict['display_survey_directly']

                personalisable_form = PersonalisableForm(
                    **personalisable_survey_dict)
                forms_index.add_child(instance=personalisable_form)
                if personalisable_survey.status_string == 'draft'\
                        or personalisable_survey.status_string == 'expired':
                    personalisable_form.specific.unpublish()
                else:
                    personalisable_form.save_revision().publish()

                if personalisable_survey.terms_and_conditions.first():
                    form_tc = FooterPage.objects.child_of(forms_tc).filter(
                        title=personalisable_survey.terms_and_conditions.first(
                        ).terms_and_conditions.title)
                    personalisable_survey.terms_and_conditions.first()\
                        .terms_and_conditions
                    FormTermsConditions.objects.create(
                        page=personalisable_form,
                        terms_and_conditions=form_tc.first())

                for personalisable_form_field in \
                    PersonalisableSurveyFormField.objects.filter(
                        page_id=personalisable_survey_id):
                    personalisable_form_field_dict = {}

                    for item in personalisable_form_field.__dict__.items():
                        personalisable_form_field_dict[item[0]] = item[1]
                    personalisable_form_field_dict[
                        'page_id'] = PersonalisableForm.objects.filter(
                            id=personalisable_form.id).first().id
                    del personalisable_form_field_dict['_state']
                    del personalisable_form_field_dict['id']

                    PersonalisableFormField.objects.create(
                        **personalisable_form_field_dict)
                for submission in \
                    MoloSurveySubmission.objects.filter(
                        page_id=personalisable_survey_id):
                    submission_dict = {}
                    for item in submission.__dict__.items():
                        submission_dict[item[0]] = item[1]
                    del submission_dict['_state']
                    del submission_dict['id']
                    submission_dict['submit_time'] = \
                        submission_dict['created_at']
                    del submission_dict['created_at']
                    submission_dict['page_id'] = personalisable_form.id
                    form_submission = MoloFormSubmission.objects.create(
                        **submission_dict)
                    form_submission.submit_time =\
                        submission_dict['submit_time']
                    form_submission.save()
            for key in translated_survey:
                main_form = PersonalisableForm.objects.descendant_of(
                    forms_index).get(slug="form-%s" % key).specific
                translated_form = PersonalisableForm.objects.descendant_of(
                    forms_index).get(slug="form-%s" %
                                     translated_survey[key]).specific
                main_form.translated_pages.add(translated_form)
                translated_form.translated_pages.add(main_form)
            print("Migration of Personalisable Survey is Done")

        # Migrate Survey User Group to Form
        for segment_user_group in SegmentUserGroup.objects.all():
            segment_user_group_dict = {}
            for item in segment_user_group.__dict__.items():
                segment_user_group_dict[item[0]] = item[1]
            del segment_user_group_dict['_state']
            del segment_user_group_dict['id']
            segment_user_group_dict['name'] = \
                "form-" + segment_user_group_dict['name']

            FormsSegmentUserGroup.objects.create(**segment_user_group_dict)
        print("Migration of User Group is Done")

        # Migrate Survey Page View
        for view in MoloSurveyPageView.objects.all().iterator():
            view_dict = {}
            for item in view.__dict__.items():
                if item[0] not in ('id', '_state'):
                    view_dict[item[0]] = item[1]
            form_page_view = MoloFormPageView(**view_dict)
            form_page_view.save()
            form_page_view.visited_at = view_dict["visited_at"]
            form_page_view.save()
        print("Migration of PageView is Done")

        # Migrate Survey Rules to Form
        for segment in Segment.objects.all().iterator():
            submission_rules = \
                SurveySubmissionDataRule.objects.filter(
                    segment_id=segment.id).all()
            for submission_rule in submission_rules:
                rule_dict = {}
                for item in submission_rule.__dict__.items():
                    if item[0] not in ('id', '_state'):
                        rule_dict[item[0]] = item[1]
                survey_slug = MoloSurveyPage.objects.filter(
                    id=rule_dict["survey_id"]).first().slug
                form_id = MoloFormPage.objects.filter(slug="form-" +
                                                      survey_slug).first().id
                rule_dict["form_id"] = form_id
                del rule_dict["survey_id"]
                FormSubmissionDataRule.objects.create(**rule_dict)
                submission_rule.delete()
                segment.save()

            response_rules = SurveyResponseRule.objects.filter(
                segment_id=segment.id).all()
            for response_rule in response_rules:
                rule_dict = {}
                for item in response_rule.__dict__.items():
                    if item[0] not in ('id', '_state'):
                        rule_dict[item[0]] = item[1]
                survey_slug = MoloSurveyPage.objects.filter(
                    id=rule_dict["survey_id"]).first().slug
                form_id = MoloFormPage.objects.filter(slug="form-" +
                                                      survey_slug).first().id
                rule_dict["form_id"] = form_id
                del rule_dict["survey_id"]
                FormResponseRule.objects.create(**rule_dict)
                response_rule.delete()
                segment.save()

            article_rules = ArticleTagRule.objects.filter(
                segment_id=segment.id).all()
            for article_rule in article_rules:
                rule_dict = {}
                for item in article_rule.__dict__.items():
                    if item[0] not in ('id', '_state'):
                        rule_dict[item[0]] = item[1]
                FormsArticleTagRule.objects.create(**rule_dict)
                article_rule.delete()
                segment.save()

            combination_rules = CombinationRule.objects.filter(
                segment_id=segment.id).all()
            for combination_rule in combination_rules:
                rule_dict = {}
                for item in combination_rule.__dict__.items():
                    if item[0] not in ('id', '_state'):
                        rule_dict[item[0]] = item[1]
                FormCombinationRule.objects.create(**rule_dict)
                combination_rule.delete()
                segment.save()

            group_rules = GroupMembershipRule.objects.filter(
                segment_id=segment.id).all()
            for group_rule in group_rules:
                rule_dict = {}
                for item in group_rule.__dict__.items():
                    if item[0] not in ('id', '_state'):
                        rule_dict[item[0]] = item[1]
                survey_group = SegmentUserGroup.objects.filter(
                    id=rule_dict["group_id"]).first()
                form_group = FormsSegmentUserGroup.objects.filter(
                    name="form-" + survey_group.name).first()
                rule_dict["group_id"] = form_group.id
                FormGroupMembershipRule.objects.create(**rule_dict)
                group_rule.delete()
                segment.save()
        print("Migration of Survey Rules to Form is Done")
        print("*" * 10, "Migration is Done", "*" * 10)
コード例 #11
0
    def test__doesnt_remove_data_from_other_sites(self):
        user2 = User.objects.create_user(
            'test2', '*****@*****.**', 'test2')
        user2.profile.site = self.main2.get_site()
        user2.profile.save()

        # Create content
        section_index_2 = SectionIndexPage.objects.child_of(self.main2).first()
        section = self.mk_section(section_index_2, title='Section 2')
        article = self.mk_article(
            parent=section, title='Article 2')

        # Note: this 'site' attr is the django site, not the wagtail one
        MoloComment.objects.create(
            content_type=self.content_type,
            site=Site.objects.get_current(),
            object_pk=article.pk,
            user=user2,
            comment="Here's a 2nd comment",
            submit_date=timezone.now())

        form_2 = MoloFormPage(
            title='Form 2',
            slug='form-2',
        )
        section_index_2.add_child(instance=form_2)
        form_2.save_revision().publish()
        MoloFormSubmission.objects.create(
            form_data='{"checkbox-question": ["option 1", "option 2"]}',
            user=user2,
            page_id=form_2.pk
        )

        profile2 = user2.profile
        sq_index_2 = SecurityQuestionIndexPage.objects.child_of(
            self.main2).first()
        sec_q = SecurityQuestion(title='Sec Question 2')
        sq_index_2.add_child(instance=sec_q)
        sec_q.save_revision().publish()
        SecurityAnswer.objects.create(
            user=profile2, question=sec_q, answer="Sec Answer 2")

        out = StringIO()
        call_command(
            'remove_deprecated_site_data',
            profile2.site.pk, '--commit', stdout=out
        )

        comments = MoloComment.objects.all()
        self.assertEqual(comments.count(), 1)
        self.assertNotEqual(comments.first().user, user2)

        submissions = MoloFormSubmission.objects.all()
        self.assertEqual(submissions.count(), 1)
        self.assertNotEqual(submissions.first().user, user2)

        answers = SecurityAnswer.objects.all()
        self.assertEqual(answers.count(), 1)
        self.assertNotEqual(answers.first().user, user2)

        users = User.objects.filter(username__contains='test')
        self.assertEqual(users.count(), 1)
        self.assertNotEqual(users.first(), user2)

        self.assertEqual(UserProfile.objects.filter(
            site=profile2.site.pk).count(), 0)

        self.assertIn('Found 1 profiles for site 5', out.getvalue())
        self.assertIn('Found 0 staff profiles', out.getvalue())
コード例 #12
0
class TestSkipLogicEveryPage(TestCase, MoloTestCaseMixin):
    def setUp(self):
        self.mk_main()
        self.form = MoloFormPage(
            title='Test Form',
            slug='test-form',
        )
        self.another_form = MoloFormPage(
            title='Another Test Form',
            slug='another-test-form',
        )
        self.section_index.add_child(instance=self.form)
        self.form.save_revision().publish()
        self.section_index.add_child(instance=self.another_form)
        self.another_form.save_revision().publish()
        field_choices = ['next', 'end']
        self.fourth_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=4,
            label='A random animal',
            field_type='dropdown',
            skip_logic=skip_logic_data(
                field_choices,
                field_choices,
            ),
            required=True)
        self.first_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=1,
            label='Your other favourite animal',
            field_type='dropdown',
            skip_logic=skip_logic_data(
                field_choices + ['question', 'form'],
                field_choices + ['question', 'form'],
                question=self.fourth_field,
                form=self.another_form,
            ),
            required=True)
        self.second_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=2,
            label='Your favourite animal',
            field_type='dropdown',
            skip_logic=skip_logic_data(
                field_choices,
                field_choices,
            ),
            required=True)
        self.third_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=3,
            label='Your least favourite animal',
            field_type='dropdown',
            skip_logic=skip_logic_data(
                field_choices,
                field_choices,
            ),
            required=True)
        self.paginator = SkipLogicPaginator(self.form.get_form_fields())

    def test_initialises_correctly(self):
        self.assertEqual(self.paginator.page_breaks, [0, 1, 2, 3, 4])
        self.assertEqual(self.paginator.num_pages, 4)

    def test_first_question_skip_to_last(self):
        paginator = SkipLogicPaginator(
            self.form.get_form_fields(),
            {self.first_field.clean_name: 'question'},
        )
        self.assertEqual(paginator.previous_page, 1)
        self.assertEqual(paginator.next_page, 4)
        page = paginator.page(paginator.next_page)
        self.assertEqual(page.object_list, [self.fourth_field])
        self.assertEqual(page.number, 4)

    def test_first_question_skip_to_next(self):
        paginator = SkipLogicPaginator(
            self.form.get_form_fields(),
            {self.first_field.clean_name: 'next'},
        )
        self.assertEqual(paginator.previous_page, 1)
        self.assertEqual(paginator.next_page, 2)
        page = paginator.page(paginator.next_page)
        self.assertEqual(page.object_list, [self.second_field])
        self.assertEqual(page.number, 2)

    def test_first_question_skip_to_form(self):
        paginator = SkipLogicPaginator(
            self.form.get_form_fields(),
            {self.first_field.clean_name: 'form'},
        )
        self.assertEqual(paginator.previous_page, 1)
        page = paginator.page(1)
        self.assertFalse(page.has_next())
コード例 #13
0
class TestSkipLogicPaginator(TestCase, MoloTestCaseMixin):
    def setUp(self):
        self.mk_main()
        self.form = MoloFormPage(
            title='Test Form',
            slug='test-form',
        )
        self.section_index.add_child(instance=self.form)
        self.form.save_revision().publish()
        self.first_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=1,
            label='Your other favourite animal',
            field_type='singleline',
            required=True)
        self.fourth_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=4,
            label='A random animal',
            field_type='singleline',
            required=True)
        field_choices = ['next', 'end', 'question']
        self.second_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=2,
            label='Your favourite animal',
            field_type='dropdown',
            skip_logic=skip_logic_data(
                field_choices,
                field_choices,
                question=self.fourth_field,
            ),
            required=True)
        self.third_field = MoloFormField.objects.create(
            page=self.form,
            sort_order=3,
            label='Your least favourite animal',
            field_type='dropdown',
            skip_logic=skip_logic_data(
                field_choices,
                field_choices,
                question=self.fourth_field,
            ),
            required=True)
        self.paginator = SkipLogicPaginator(self.form.get_form_fields())

    def test_correct_num_pages(self):
        self.assertEqual(self.paginator.num_pages, 3)

    def test_page_breaks_correct(self):
        self.assertEqual(self.paginator.page_breaks, [0, 2, 3, 4])

    def test_first_page_correct(self):
        page = self.paginator.page(1)
        self.assertEqual(
            page.object_list,
            [self.first_field, self.second_field],
        )
        self.assertTrue(page.has_next())

    def test_second_page_correct(self):
        page = self.paginator.page(2)
        self.assertEqual(page.object_list, [self.third_field])
        self.assertTrue(page.has_next())

    def test_last_page_correct(self):
        last_page = self.paginator.page(3)
        self.assertEqual(last_page.object_list, [self.fourth_field])
        self.assertFalse(last_page.has_next())

    def test_is_end_if_skip_logic(self):
        paginator = SkipLogicPaginator(self.form.get_form_fields(),
                                       {self.second_field.clean_name: 'end'})
        first_page = paginator.page(1)
        self.assertFalse(first_page.has_next())

    def test_skip_question_if_skip_logic(self):
        paginator = SkipLogicPaginator(
            self.form.get_form_fields(),
            {self.second_field.clean_name: 'question'})
        page = paginator.page(1)
        next_page_number = page.next_page_number()
        self.assertEqual(next_page_number, 3)
        second_page = paginator.page(next_page_number)
        self.assertEqual(second_page.object_list, [self.fourth_field])

    def test_first_question_skip_to_next(self):
        paginator = SkipLogicPaginator(
            self.form.get_form_fields(),
            {self.second_field.clean_name: 'next'},
        )
        self.assertEqual(paginator.previous_page, 1)
        self.assertEqual(paginator.next_page, 2)
        page = paginator.page(paginator.next_page)
        self.assertEqual(page.object_list, [self.third_field])
        self.assertEqual(page.number, 2)

    def test_previous_page_if_skip_a_page(self):
        paginator = SkipLogicPaginator(
            self.form.get_form_fields(), {
                self.first_field.clean_name: 'python',
                self.second_field.clean_name: 'question',
            })
        page = paginator.page(1)
        next_page_number = page.next_page_number()
        self.assertEqual(next_page_number, 3)
        second_page = paginator.page(next_page_number)
        previous_page_number = second_page.previous_page_number()
        self.assertEqual(previous_page_number, 1)
        self.assertEqual(
            paginator.page(previous_page_number).object_list,
            [self.first_field, self.second_field],
        )

    def test_question_progression_index(self):
        paginator = SkipLogicPaginator(
            self.form.get_form_fields(), {
                self.first_field.clean_name: 'python',
                self.second_field.clean_name: 'question',
            })
        self.assertEqual(paginator.previous_page, 1)
        self.assertEqual(paginator.last_question_index, 1)
        self.assertEqual(paginator.next_page, 3)
        self.assertEqual(paginator.next_question_index, 3)

    def test_no_data_index(self):
        paginator = SkipLogicPaginator(self.form.get_form_fields())
        self.assertEqual(paginator.previous_page, 1)
        self.assertEqual(paginator.next_page, 1)
        self.assertEqual(paginator.next_question_index, 0)

    def test_no_data_index_with_checkbox(self):
        self.first_field.field_type = 'checkbox'
        self.first_field.skip_logic = skip_logic_data(
            ['', ''],
            ['next', 'end'],
        )
        self.first_field.save()
        paginator = SkipLogicPaginator(
            self.form.get_form_fields(),
            data={'csrf': 'dummy'},
        )
        self.assertEqual(paginator.previous_page, 1)
        self.assertEqual(paginator.last_question_index, 0)
        self.assertEqual(paginator.next_page, 2)
        self.assertEqual(paginator.next_question_index, 1)

    def test_single_question_quiz_with_skip_logic_pages_correctly(self):
        self.first_field.delete()
        self.third_field.delete()
        self.fourth_field.delete()
        paginator = SkipLogicPaginator(self.form.get_form_fields())
        self.assertEqual(paginator.num_pages, 1)