Beispiel #1
0
 def test_answer_meta_image_undefined(self):
     """ Answer page's meta image is undefined if social image is
     not provided
     """
     answer = Answer()
     answer.save()
     page = self.create_answer_page(answer_base=answer)
     self.assertIsNone(page.meta_image)
 def test_answer_meta_image_undefined(self):
     """ Answer page's meta image is undefined if social image is
     not provided
     """
     answer = Answer()
     answer.save()
     page = self.create_answer_page(answer_base=answer)
     self.assertIsNone(page.meta_image)
    def test_export_script_assemble_output(self):
        answer = Answer(id=1234)
        answer.save()
        page = AnswerPage(slug='mock-question1-en-1234',
                          title='Mock question1')
        page.answer_base = answer
        page.question = 'Mock question1'
        helpers.publish_page(page)

        output = assemble_output()[0]
        self.assertEqual(output.get('ASK_ID'), 1234)
        self.assertEqual(output.get('URL'), '/mock-question1-en-1234/')
        self.assertEqual(output.get('Question'), 'Mock question1')
Beispiel #4
0
    def test_export_script_assemble_output(self):
        answer = Answer(id=1234)
        answer.save()
        page = AnswerPage(
            slug='mock-question1-en-1234',
            title='Mock question1')
        page.answer_base = answer
        page.question = 'Mock question1'
        helpers.publish_page(page)

        output = assemble_output()[0]
        self.assertEqual(output.get('ASK_ID'), 1234)
        self.assertEqual(output.get('URL'), '/mock-question1-en-1234/')
        self.assertEqual(output.get('Question'), 'Mock question1')
Beispiel #5
0
    def test_export_script_assemble_output(self):
        answer = Answer(id=1234)
        answer.save()
        page = AnswerPage(slug='mock-question1-en-1234',
                          title='Mock question1')
        page.answer_base = answer
        page.question = 'Mock question1'
        page.answer_content = StreamValue(page.answer_content.stream_block,
                                          [{
                                              'type': 'text',
                                              'value': 'Mock answer'
                                          }], True)
        helpers.publish_page(page)

        output = assemble_output()[0]
        self.assertEqual(output.get('ASK_ID'), 1234)
        self.assertEqual(output.get('URL'), '/mock-question1-en-1234/')
        self.assertEqual(output.get('Question'), 'Mock question1')
    def test_export_script_assemble_output(self):
        answer = Answer(id=1234)
        answer.save()
        page = AnswerPage(
            slug="mock-question1-en-1234", title="Mock question1"
        )
        page.answer_base = answer
        page.question = "Mock question1"
        page.answer_content = StreamValue(
            page.answer_content.stream_block,
            [{"type": "text", "value": {"content": "Mock answer"}}],
            True,
        )
        helpers.publish_page(page)

        output = assemble_output()[0]
        self.assertEqual(output.get("ASK_ID"), 1234)
        self.assertEqual(output.get("URL"), "/mock-question1-en-1234/")
        self.assertEqual(output.get("Question"), "Mock question1")
Beispiel #7
0
    def test_export_script_assemble_output(self):
        answer = Answer(id=1234)
        answer.save()
        page = AnswerPage(
            slug='mock-question1-en-1234',
            title='Mock question1')
        page.answer_base = answer
        page.question = 'Mock question1'
        page.answer_content = StreamValue(
            page.answer_content.stream_block, [{
                'type': 'text',
                'value': 'Mock answer'
            }], True
        )
        helpers.publish_page(page)

        output = assemble_output()[0]
        self.assertEqual(output.get('ASK_ID'), 1234)
        self.assertEqual(output.get('URL'), '/mock-question1-en-1234/')
        self.assertEqual(output.get('Question'), 'Mock question1')
Beispiel #8
0
 def test_answer_string_method(self):
     test_answer = Answer(question="Test question?")
     test_answer.save()
     self.assertEqual(test_answer.__str__(), test_answer.question)
Beispiel #9
0
class AnswerPageTestCase(TestCase):

    fixtures = ['ask_tests', 'portal_topics']

    def create_answer_page(self, **kwargs):
        kwargs.setdefault(
            'path', get_free_path(apps, self.english_parent_page))
        kwargs.setdefault('depth', self.english_parent_page.depth + 1)
        kwargs.setdefault('slug', 'mock-answer-page-en-1234')
        kwargs.setdefault('title', 'Mock answer page title')
        page = mommy.prepare(AnswerPage, **kwargs)
        page.save()
        return page

    def setUp(self):
        self.test_user = User.objects.get(pk=1)
        self.factory = RequestFactory()
        ROOT_PAGE = HomePage.objects.get(slug='cfgov')
        self.category = mommy.make(
            Category, name='stub_cat', name_es='que', slug='stub-cat')
        self.category.save()
        self.test_image = mommy.make(CFGOVImage)
        self.test_image2 = mommy.make(CFGOVImage)
        self.next_step = mommy.make(NextStep, title='stub_step')
        self.portal_topic = mommy.make(
            PortalTopic,
            heading='test topic',
            heading_es='prueba tema')
        page_clean = mock.patch('ask_cfpb.models.pages.CFGOVPage.clean')
        page_clean.start()
        self.addCleanup(page_clean.stop)
        self.portal_page = SublandingPage(
            title='test portal page',
            slug='test-portal-page',
            portal_topic=self.portal_topic,
            language='en'
        )
        ROOT_PAGE.add_child(instance=self.portal_page)
        self.portal_page.save()
        self.portal_page.save_revision().publish()
        self.portal_page_es = SublandingPage(
            title='test portal page',
            slug='test-portal-page-es',
            portal_topic=self.portal_topic,
            language='es'
        )
        ROOT_PAGE.add_child(instance=self.portal_page_es)
        self.portal_page_es.save()
        self.portal_page_es.save_revision().publish()
        self.english_parent_page = get_or_create_page(
            apps,
            'ask_cfpb',
            'AnswerLandingPage',
            'Ask CFPB',
            ENGLISH_PARENT_SLUG,
            ROOT_PAGE,
            language='en',
            live=True)
        self.spanish_parent_page = get_or_create_page(
            apps,
            'ask_cfpb',
            'AnswerLandingPage',
            'Obtener respuestas',
            SPANISH_PARENT_SLUG,
            ROOT_PAGE,
            language='es',
            live=True)
        self.tag_results_page_en = get_or_create_page(
            apps,
            'ask_cfpb',
            'TagResultsPage',
            'Tag results page',
            'search-by-tag',
            ROOT_PAGE,
            language='en',
            live=True)
        self.tag_results_page_es = get_or_create_page(
            apps,
            'ask_cfpb',
            'TagResultsPage',
            'Tag results page',
            'buscar-por-etiqueta',
            ROOT_PAGE,
            language='es',
            live=True)
        self.answer1234 = Answer(id=1234)
        self.answer1234.save()
        self.page1 = AnswerPage(
            language='en',
            answer_base=self.answer1234,
            slug='mock-question-en-1234',
            title='Mock question1',
            answer_content='Mock answer 1',
            question='Mock question1',
            search_tags='hippodrome')
        self.english_parent_page.add_child(instance=self.page1)
        self.page1.save_revision().publish()
        self.page1_es = AnswerPage(
            language='es',
            slug='mock-spanish-question1-es-1234',
            title='Mock Spanish question1',
            answer_base=self.answer1234,
            answer_content='Mock Spanish answer',
            question='Mock Spanish question1',
            search_tags='hipotecas')
        self.spanish_parent_page.add_child(instance=self.page1_es)
        self.page1_es.save_revision().publish()
        self.answer5678 = Answer(id=5678)
        self.answer5678.save()
        self.page2 = AnswerPage(
            language='en',
            slug='mock-question2-en-5678',
            title='Mock question2',
            answer_base=self.answer5678,
            answer_content='Mock answer 2',
            question='Mock question2',
            search_tags='hippodrome')
        self.english_parent_page.add_child(instance=self.page2)
        self.page2.save_revision().publish()

    def test_tag_results_page_templates(self):
        self.assertEqual(
            self.tag_results_page_es.get_template(HttpRequest()),
            self.tag_results_page_en.get_template(HttpRequest()))

    def test_tag_results_page_context_language(self):
        context = self.tag_results_page_es.get_context(HttpRequest())
        self.assertEqual(
            context.get('breadcrumb_items')[0]['title'],
            'Obtener respuestas')

    def test_english_page_context(self):
        from v1.models.snippets import ReusableText
        from ask_cfpb.models.pages import get_reusable_text_snippet
        rt = ReusableText(title='About us (For consumers)')
        rt.save()
        page = self.page1
        page.language = 'en'
        page.save()
        test_context = page.get_context(HttpRequest())
        self.assertEqual(
            test_context['about_us'],
            get_reusable_text_snippet('About us (For consumers)'))

    def test_routable_tag_page_base_returns_404(self):
        page = self.tag_results_page_en
        response = self.client.get(
            page.url + page.reverse_subpage(
                'tag_base'))
        self.assertEqual(response.status_code, 404)

    def test_routable_tag_page_handles_bad_tag(self):
        page = self.tag_results_page_en
        response = self.client.get(
            page.url + page.reverse_subpage(
                'tag_search',
                kwargs={'tag': 'hippopotamus'}))
        self.assertEqual(response.status_code, 200)

    def test_routable_tag_page_handles_bad_pagination(self):
        page = self.tag_results_page_en
        response = self.client.get(
            page.url + page.reverse_subpage(
                'tag_search',
                kwargs={'tag': 'hippodrome'}), {'page': '100'})
        self.assertEqual(response.status_code, 200)

    def test_routable_tag_page_valid_tag_returns_200(self):
        page = self.tag_results_page_en
        response = self.client.get(
            page.url + page.reverse_subpage(
                'tag_search',
                kwargs={'tag': 'hippodrome'}))
        self.assertEqual(response.status_code, 200)

    def test_routable_tag_page_returns_url_suffix(self):
        page = self.tag_results_page_en
        response = page.reverse_subpage(
            'tag_search', kwargs={'tag': 'hippodrome'})
        self.assertEqual(response, 'hippodrome/')

    def test_view_answer_exact_slug(self):
        page = self.page1
        page.slug = 'mock-answer-en-1234'
        page.save()
        revision = page.save_revision()
        revision.publish()
        response = self.client.get(reverse(
            'ask-english-answer', args=['mock-answer', 'en', 1234]))
        self.assertEqual(response.status_code, 200)

    def test_view_answer_301_for_healed_slug(self):
        page = self.page1
        revision = page.save_revision()
        revision.publish()
        response = self.client.get(reverse(
            'ask-english-answer', args=['mock-slug', 'en', 1234]))
        self.assertEqual(response.status_code, 301)

    def test_view_answer_redirected(self):
        page = self.page1
        page.redirect_to = self.page2.answer_base
        page.save()
        revision = page.save_revision()
        revision.publish()
        response_302 = self.client.get(reverse(
            'ask-english-answer', args=['mocking-answer-page', 'en', 1234]))
        self.assertTrue(isinstance(response_302, HttpResponse))
        self.assertEqual(response_302.status_code, 301)

    def test_spanish_answer_page_handles_referrer_with_unicode_accents(self):
        referrer_unicode = (
            'https://www.consumerfinance.gov/es/obtener-respuestas/'
            'buscar-por-etiqueta/empresas_de_informes_de_cr\xe9dito/')
        spanish_page = self.page1_es
        request = HttpRequest()
        request.POST['referrer'] = referrer_unicode
        response = spanish_page.serve(request)
        self.assertEqual(response.status_code, 200)

    def test_page_string_no_base(self):
        test_page = self.create_answer_page()
        result = test_page.__str__()
        self.assertEqual(result, test_page.title)

    def test_page_string_with_base(self):
        page = self.page1
        self.assertTrue(page.answer_base)
        result = page.__str__()
        self.assertEqual(result, "{}: {}".format(
            page.answer_base.pk, page.title))

    def test_search_tags(self):
        """Test the list produced by page.clean_search_tags()"""
        page = self.page1
        page.search_tags = 'Chutes, Ladders'
        page.save_revision().publish()
        taglist = page.clean_search_tags
        for name in ['Chutes', 'Ladders']:
            self.assertIn(name, taglist)

    def test_english_header_and_footer(self):
        english_answer_page_response = self.client.get(reverse(
            'ask-english-answer',
            args=['mock-question', 'en', 1234]))
        self.assertContains(
            english_answer_page_response,
            'An official website of the United States government')
        self.assertNotContains(
            english_answer_page_response,
            'Un sitio web oficial del gobierno federal de los Estados Unidos')
        self.assertContains(
            english_answer_page_response,
            'https://usa.gov/')
        self.assertNotContains(
            english_answer_page_response,
            'https://gobiernousa.gov/')

    def test_spanish_header_and_footer(self):
        spanish_answer_page_response = self.client.get(reverse(
            'ask-spanish-answer',
            args=['mock-spanish-question1', 'es', 1234]))
        self.assertContains(
            spanish_answer_page_response,
            'Un sitio web oficial del gobierno federal de los Estados Unidos'
        )
        self.assertNotContains(
            spanish_answer_page_response,
            'An official website of the United States government'
        )
        self.assertContains(
            spanish_answer_page_response,
            'https://gobiernousa.gov/')
        self.assertNotContains(
            spanish_answer_page_response,
            'https://usa.gov/')

    def test_category_str(self):
        category = self.category
        self.assertEqual(category.__str__(), category.name)

    def test_portal_topic_featured_answers(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        self.assertIn(page, self.portal_topic.featured_answers('en'))

    def test_nextstep_str(self):
        next_step = self.next_step
        self.assertEqual(next_step.__str__(), next_step.title)

    def test_status_string(self):
        with translation.override('en'):
            page1 = self.page1
            self.assertEqual(
                (page1.status_string),
                'live + draft')

    def test_status_string_redirected(self):
        with translation.override('en'):
            page1 = self.page1
            page1.redirect_to_page = self.page2
            page1.save()
            page1.get_latest_revision().publish()
            self.assertEqual(
                (page1.status_string),
                "redirected")
            page1.unpublish()
            self.assertEqual(
                page1.status_string, ("redirected but not live"))

    def test_get_ask_breadcrumbs(self):
        from ask_cfpb.models import get_ask_breadcrumbs
        breadcrumbs = get_ask_breadcrumbs()
        self.assertEqual(len(breadcrumbs), 1)
        self.assertEqual(breadcrumbs[0]['title'], 'Ask CFPB')

    def test_landing_page_context_no_featured_answer(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = False
        page.save_revision().publish()
        mock_site = mock.Mock()
        mock_site.hostname = 'localhost'
        mock_request = HttpRequest()
        mock_request.site = mock_site
        landing_page = self.english_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context['portal_cards']), 0)

    def test_landing_page_context(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        mock_site = mock.Mock()
        mock_site.hostname = 'localhost'
        mock_request = HttpRequest()
        mock_request.site = mock_site
        landing_page = self.english_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context['portal_cards']), 1)
        self.assertEqual(
            test_context['portal_cards'][0]['title'],
            'test topic')

    def test_spanish_landing_page_context(self):
        page = self.page1_es
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        mock_site = mock.Mock()
        mock_site.hostname = 'localhost'
        mock_request = HttpRequest()
        mock_request.site = mock_site
        landing_page = self.spanish_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context['portal_cards']), 1)
        self.assertEqual(
            test_context['portal_cards'][0]['title'],
            'prueba tema')

    def test_landing_page_context_draft_portal_page(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        self.portal_page.unpublish()
        mock_site = mock.Mock()
        mock_site.hostname = 'localhost'
        mock_request = HttpRequest()
        mock_request.site = mock_site
        landing_page = self.english_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context['portal_cards']), 0)

    def test_answer_language_page_exists(self):
        self.assertEqual(self.answer5678.english_page, self.page2)

    def test_answer_language_page_nonexistent(self):
        self.assertEqual(self.answer5678.spanish_page, None)

    def test_get_reusable_text_snippet(self):
        from ask_cfpb.models import get_reusable_text_snippet
        from v1.models.snippets import ReusableText
        test_snippet = ReusableText.objects.create(title='Test Snippet')
        self.assertEqual(
            get_reusable_text_snippet('Test Snippet'),
            test_snippet)

    def test_get_nonexistent_reusable_text_snippet(self):
        from ask_cfpb.models import get_reusable_text_snippet
        self.assertEqual(
            get_reusable_text_snippet('Nonexistent Snippet'),
            None)

    def test_get_about_us_english_standard_text(self):
        from ask_cfpb.models import get_standard_text
        from v1.models.snippets import ReusableText
        snippet_title = REUSABLE_TEXT_TITLES['about_us']['en']
        test_snippet = ReusableText.objects.create(title=snippet_title)
        self.assertEqual(
            get_standard_text('en', 'about_us'),
            test_snippet)

    def test_social_sharing_image_used(self):
        from v1.models.images import CFGOVImage
        image = CFGOVImage.objects.last()
        page = self.page1
        page.social_sharing_image = image
        page.save_revision(user=self.test_user).publish()
        self.assertEqual(page.meta_image, image)

    def test_answer_meta_image_undefined(self):
        """ Answer page's meta image is undefined if social image is
        not provided
        """
        answer = Answer()
        answer.save()
        page = self.create_answer_page(answer_base=answer)
        self.assertIsNone(page.meta_image)

    def test_answer_meta_image_uses_category_image_if_no_social_image(self):
        """ Answer page's meta image is its category's image """
        category = mommy.make(Category, category_image=self.test_image)
        page = self.page1
        page.category.add(category)
        page.save_revision()
        self.assertEqual(page.meta_image, self.test_image)

    def test_answer_split_testing_id(self):
        """Confirm AnswerPage's split_testing_id is set to its answer_base.id,
        which is checked by the core.feature_flags.in_split_testing_cluster
        flag condition when doing split testing on Ask CFPB answer pages."""
        answer = self.answer1234
        page = answer.english_page
        self.assertEqual(page.split_test_id, answer.id)

    def test_validate_pagination_number(self):
        paginator = Paginator([{'fake': 'results'}] * 30, 25)
        request = HttpRequest()
        self.assertEqual(validate_page_number(request, paginator), 1)
        request.GET.update({'page': '2'})
        self.assertEqual(validate_page_number(request, paginator), 2)
        request = HttpRequest()
        request.GET.update({'page': '1000'})
        self.assertEqual(validate_page_number(request, paginator), 1)
        request = HttpRequest()
        request.GET.update({'page': '<script>Boo</script>'})
        self.assertEqual(validate_page_number(request, paginator), 1)

    def test_schema_html_does_not_appear_when_flag_is_off(self):
        with override_settings(
                FLAGS={'HOW_TO_SCHEMA': [('boolean', False)]}):
            response = self.client.get(self.page1.url)
            self.assertNotContains(
                response,
                'itemtype="http://schema.org/HowTo"'
            )

    def test_schema_html_appears_when_flag_is_on(self):
        with override_settings(
                FLAGS={'HOW_TO_SCHEMA': [('boolean', True)]}):
            response = self.client.get(self.page1.url)
            self.assertContains(response, 'itemtype="http://schema.org/HowTo"')
class AnswerPageTest(TestCase):

    fixtures = ["ask_tests", "portal_topics"]

    def create_answer_page(self, **kwargs):
        kwargs.setdefault(
            "path", get_free_path(apps, self.english_parent_page)
        )
        kwargs.setdefault("depth", self.english_parent_page.depth + 1)
        kwargs.setdefault("slug", "mock-answer-page-en-1234")
        kwargs.setdefault("title", "Mock answer page title")
        page = baker.prepare(AnswerPage, **kwargs)
        page.save()
        return page

    def setUp(self):
        self.test_user = User.objects.get(pk=1)
        self.ROOT_PAGE = HomePage.objects.get(slug="cfgov")
        self.category = baker.make(
            Category, name="stub_cat", name_es="que", slug="stub-cat"
        )
        self.category.save()
        self.test_image = baker.make(CFGOVImage)
        self.test_image2 = baker.make(CFGOVImage)
        self.next_step = baker.make(NextStep, title="stub_step")
        self.portal_topic = baker.make(
            PortalTopic, heading="test topic", heading_es="prueba tema"
        )
        page_clean = mock.patch("ask_cfpb.models.pages.CFGOVPage.clean")
        page_clean.start()
        self.addCleanup(page_clean.stop)
        self.portal_page = SublandingPage(
            title="test portal page",
            slug="test-portal-page",
            portal_topic=self.portal_topic,
            language="en",
        )
        self.ROOT_PAGE.add_child(instance=self.portal_page)
        self.portal_page.save()
        self.portal_page.save_revision().publish()
        self.portal_page_es = SublandingPage(
            title="test portal page",
            slug="test-portal-page-es",
            portal_topic=self.portal_topic,
            language="es",
        )
        self.ROOT_PAGE.add_child(instance=self.portal_page_es)
        self.portal_page_es.save()
        self.portal_page_es.save_revision().publish()
        self.english_parent_page = get_or_create_page(
            apps,
            "ask_cfpb",
            "AnswerLandingPage",
            "Ask CFPB",
            ENGLISH_PARENT_SLUG,
            self.ROOT_PAGE,
            language="en",
            live=True,
        )
        self.spanish_parent_page = get_or_create_page(
            apps,
            "ask_cfpb",
            "AnswerLandingPage",
            "Obtener respuestas",
            SPANISH_PARENT_SLUG,
            self.ROOT_PAGE,
            language="es",
            live=True,
        )
        self.tag_results_page_en = get_or_create_page(
            apps,
            "ask_cfpb",
            "TagResultsPage",
            "Tag results page",
            "search-by-tag",
            self.ROOT_PAGE,
            language="en",
            live=True,
        )
        self.tag_results_page_es = get_or_create_page(
            apps,
            "ask_cfpb",
            "TagResultsPage",
            "Tag results page",
            "buscar-por-etiqueta",
            self.ROOT_PAGE,
            language="es",
            live=True,
        )
        self.answer1234 = Answer(id=1234)
        self.answer1234.save()
        self.page1 = AnswerPage(
            language="en",
            answer_base=self.answer1234,
            slug="mock-question-en-1234",
            title="Mock question1",
            answer_content="Mock answer 1",
            question="Mock question1",
            search_tags="hippodrome",
        )
        self.english_parent_page.add_child(instance=self.page1)
        self.page1.save_revision().publish()
        self.page1_es = AnswerPage(
            language="es",
            slug="mock-spanish-question1-es-1234",
            title="Mock Spanish question1",
            answer_base=self.answer1234,
            answer_content="Mock Spanish answer",
            question="Mock Spanish question1",
            search_tags="hipotecas",
        )
        self.spanish_parent_page.add_child(instance=self.page1_es)
        self.page1_es.save_revision().publish()
        self.answer5678 = Answer(id=5678)
        self.answer5678.save()
        self.page2 = AnswerPage(
            language="en",
            slug="mock-question2-en-5678",
            title="Mock question2",
            answer_base=self.answer5678,
            answer_content="Mock answer 2",
            question="Mock question2",
            search_tags="hippodrome",
        )
        self.english_parent_page.add_child(instance=self.page2)
        self.page2.save_revision().publish()

    def test_tag_results_page_templates(self):
        self.assertEqual(
            self.tag_results_page_es.get_template(HttpRequest()),
            self.tag_results_page_en.get_template(HttpRequest()),
        )

    def test_tag_results_page_context_language(self):
        context = self.tag_results_page_es.get_context(HttpRequest())
        self.assertEqual(
            context.get("breadcrumb_items")[0]["title"], "Obtener respuestas"
        )

    def test_answer_content_preview_word(self):
        """answer_content_preview returns truncated text by word count

        And without HTML tags.
        """

        page = self.page1
        stream_data = [
            {
                "type": "video_player",
                "id": "402b933b",
                "value": {
                    "video_url": "https://www.youtube.com/embed/wcQ1a_Gg8tI"
                },
            },
            {
                "type": "text",
                "id": "402b933c",
                "value": {
                    "content": (
                        "<p><span>"
                        "This is more than forty words: "
                        "word word word word word word word word word word "
                        "word word word word word word word word word word "
                        "word word word word word word word word word word "
                        "word word word word word word too-many."
                        "</span></p>"
                    )
                },
            },
        ]
        set_stream_data(page, "answer_content", stream_data)
        self.assertTrue(
            page.answer_content_preview().endswith("word word ...")
        )

    def test_answer_content_preview_char(self):
        """answer_content_preview returns truncated text by character count

        And without HTML tags.
        """

        page = self.page1
        stream_data = [
            {
                "type": "video_player",
                "id": "402b933b",
                "value": {
                    "video_url": "https://www.youtube.com/embed/wcQ1a_Gg8tI"
                },
            },
            {
                "type": "text",
                "id": "402b933c",
                "value": {
                    "content": (
                        "<p><span>"
                        "This a word with more than 255 characters: "
                        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
                        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
                        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
                        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
                        "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
                        "char char char char char char char char char char "
                        "char char char char char char char char char char "
                        "char char char char char char char char char char "
                        "char char char char char char too-many."
                        "</span></p>"
                    )
                },
            },
        ]
        set_stream_data(page, "answer_content", stream_data)
        self.assertTrue(page.answer_content_preview().endswith(" ..."))

    def test_english_page_context(self):
        from ask_cfpb.models.pages import get_reusable_text_snippet
        from v1.models.snippets import ReusableText

        rt = ReusableText(title="About us (For consumers)")
        rt.save()
        page = self.page1
        page.language = "en"
        page.save()
        test_context = page.get_context(HttpRequest())
        self.assertEqual(
            test_context["about_us"],
            get_reusable_text_snippet("About us (For consumers)"),
        )

    def test_get_meta_description(self):
        page = self.page1
        # Defaults to empty string
        self.assertEqual(
            page.get_meta_description(),
            ""
        )

        # Second fallback is truncated answer_content text block
        stream_data = [
            {
                "type": "video_player",
                "id": "402b933b",
                "value": {
                    "video_url": "https://www.youtube.com/embed/wcQ1a_Gg8tI"
                },
            },
            {
                "type": "text",
                "id": "402b933c",
                "value": {
                    "content": (
                        "<p><span>"
                        "This is more than forty words: "
                        "word word word word word word word word word word "
                        "word word word word word word word word word word "
                        "word word word word word word word word word word "
                        "word word word word word word too-many."
                        "</span></p>"
                    )
                },
            },
        ]
        set_stream_data(page, "answer_content", stream_data)
        self.assertTrue(page.get_meta_description().endswith("word word ..."))

        # First fallback is the short_answer
        page.short_answer = "Test short answer"
        self.assertEqual(page.get_meta_description(), page.short_answer)

        # First choice is the search_description
        page.search_description = "Test search description"
        self.assertEqual(page.get_meta_description(), page.search_description)

    def test_english_page_sibling_url(self):
        self.assertEqual(self.page1.get_sibling_url(), self.page1_es.url)

    def test_spanish_page_sibling_url(self):
        self.assertEqual(self.page1_es.get_sibling_url(), self.page1.url)

    def test_no_sibling_url_returned_for_redirected_page(self):
        self.page1_es.redirect_to_page = self.page2
        self.page1_es.save()
        self.page1_es.save_revision(user=self.test_user).publish()
        self.assertEqual(self.page1.get_sibling_url(), None)

    def test_no_sibling_url_returned_for_draft_page(self):
        self.page1.unpublish()
        self.assertEqual(self.page1_es.get_sibling_url(), None)

    def test_routable_tag_page_base_returns_404(self):
        page = self.tag_results_page_en
        response = self.client.get(page.url + page.reverse_subpage("tag_base"))
        self.assertEqual(response.status_code, 404)

    def test_routable_tag_page_handles_bad_tag(self):
        page = self.tag_results_page_en
        response = self.client.get(
            page.url
            + page.reverse_subpage(
                "tag_search", kwargs={"tag": "hippopotamus"}
            )
        )
        self.assertEqual(response.status_code, 200)

    def test_routable_tag_page_handles_bad_pagination(self):
        page = self.tag_results_page_en
        response = self.client.get(
            page.url
            + page.reverse_subpage("tag_search", kwargs={"tag": "hippodrome"}),
            {"page": "100"},
        )
        self.assertEqual(response.status_code, 200)

    def test_routable_tag_page_valid_tag_returns_200(self):
        page = self.tag_results_page_en
        response = self.client.get(
            page.url
            + page.reverse_subpage("tag_search", kwargs={"tag": "hippodrome"})
        )
        self.assertEqual(response.status_code, 200)

    def test_routable_tag_page_returns_url_suffix(self):
        page = self.tag_results_page_en
        response = page.reverse_subpage(
            "tag_search", kwargs={"tag": "hippodrome"}
        )
        self.assertEqual(response, "hippodrome/")

    def test_view_answer_exact_slug(self):
        page = self.page1
        page.slug = "mock-answer-en-1234"
        page.save()
        revision = page.save_revision()
        revision.publish()
        response = self.client.get(
            reverse("ask-english-answer", args=["mock-answer", "en", 1234])
        )
        self.assertEqual(response.status_code, 200)

    def test_view_answer_301_for_healed_slug(self):
        page = self.page1
        revision = page.save_revision()
        revision.publish()
        response = self.client.get(
            reverse("ask-english-answer", args=["mock-slug", "en", 1234])
        )
        self.assertEqual(response.status_code, 301)

    def test_view_answer_redirected(self):
        page = self.page1
        page.redirect_to = self.page2.answer_base
        page.save()
        revision = page.save_revision()
        revision.publish()
        response_302 = self.client.get(
            reverse(
                "ask-english-answer", args=["mocking-answer-page", "en", 1234]
            )
        )
        self.assertTrue(isinstance(response_302, HttpResponse))
        self.assertEqual(response_302.status_code, 301)

    def test_spanish_answer_page_handles_referrer_with_unicode_accents(self):
        referrer_unicode = (
            "https://www.consumerfinance.gov/es/obtener-respuestas/"
            "buscar-por-etiqueta/empresas_de_informes_de_cr\xe9dito/"
        )
        spanish_page = self.page1_es
        request = HttpRequest()
        request.POST["referrer"] = referrer_unicode
        response = spanish_page.serve(request)
        self.assertEqual(response.status_code, 200)

    def test_page_string_no_base(self):
        test_page = self.create_answer_page()
        result = test_page.__str__()
        self.assertEqual(result, test_page.title)

    def test_page_string_with_base(self):
        page = self.page1
        self.assertTrue(page.answer_base)
        result = page.__str__()
        self.assertEqual(
            result, "{}: {}".format(page.answer_base.pk, page.title)
        )

    def test_search_tags(self):
        """Test the list produced by page.clean_search_tags()."""
        page = self.page1
        page.search_tags = "Chutes, Ladders"
        page.save_revision().publish()
        taglist = page.clean_search_tags
        for name in ["Chutes", "Ladders"]:
            self.assertIn(name, taglist)

    def test_english_header_and_footer(self):
        english_answer_page_response = self.client.get(
            reverse("ask-english-answer", args=["mock-question", "en", 1234])
        )
        self.assertContains(
            english_answer_page_response,
            "An official website of the United States government",
        )
        self.assertNotContains(
            english_answer_page_response,
            "Un sitio web oficial del gobierno federal de los Estados Unidos",
        )
        self.assertContains(english_answer_page_response, "https://usa.gov/")
        self.assertNotContains(
            english_answer_page_response, "https://gobiernousa.gov/"
        )

    def test_spanish_header_and_footer(self):
        spanish_answer_page_response = self.client.get(
            reverse(
                "ask-spanish-answer",
                args=["mock-spanish-question1", "es", 1234],
            )
        )
        self.assertContains(
            spanish_answer_page_response,
            "Un sitio web oficial del gobierno federal de los Estados Unidos",
        )
        self.assertNotContains(
            spanish_answer_page_response,
            "An official website of the United States government",
        )
        self.assertContains(
            spanish_answer_page_response, "https://gobiernousa.gov/"
        )
        self.assertNotContains(
            spanish_answer_page_response, "https://usa.gov/"
        )

    def test_category_str(self):
        category = self.category
        self.assertEqual(category.__str__(), category.name)

    def test_portal_topic_featured_answers(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        self.assertIn(page, self.portal_topic.featured_answers("en"))

    def test_nextstep_str(self):
        next_step = self.next_step
        self.assertEqual(next_step.__str__(), next_step.title)

    def test_status_string(self):
        with translation.override("en"):
            page1 = self.page1
            self.assertEqual(page1.status_string, "live + draft")

    def test_status_string_redirected(self):
        with translation.override("en"):
            page1 = self.page1
            page1.redirect_to_page = self.page2
            page1.save()
            page1.get_latest_revision().publish()
            self.assertEqual(page1.status_string, "redirected")
            page1.unpublish()
            self.assertEqual(page1.status_string, "redirected but not live")

    def test_get_ask_breadcrumbs(self):
        from ask_cfpb.models import get_ask_breadcrumbs

        breadcrumbs = get_ask_breadcrumbs()
        self.assertEqual(len(breadcrumbs), 1)
        self.assertEqual(breadcrumbs[0]["title"], "Ask CFPB")

    def test_landing_page_context_no_featured_answer(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = False
        page.save_revision().publish()
        mock_site = mock.Mock()
        mock_site.hostname = "localhost"
        mock_request = HttpRequest()
        landing_page = self.english_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context["portal_cards"]), 0)

    def test_landing_page_context(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        mock_site = mock.Mock()
        mock_site.hostname = "localhost"
        mock_request = HttpRequest()
        landing_page = self.english_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context["portal_cards"]), 1)
        self.assertEqual(
            test_context["portal_cards"][0]["title"], "test topic"
        )

    def test_spanish_landing_page_context(self):
        page = self.page1_es
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        mock_site = mock.Mock()
        mock_site.hostname = "localhost"
        mock_request = HttpRequest()
        landing_page = self.spanish_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context["portal_cards"]), 1)
        self.assertEqual(
            test_context["portal_cards"][0]["title"], "prueba tema"
        )

    def test_landing_page_context_draft_portal_page(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        self.portal_page.unpublish()
        mock_site = mock.Mock()
        mock_site.hostname = "localhost"
        mock_request = HttpRequest()
        landing_page = self.english_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context["portal_cards"]), 0)

    def test_answer_language_page_exists(self):
        self.assertEqual(self.answer5678.english_page, self.page2)

    def test_answer_language_page_nonexistent(self):
        self.assertEqual(self.answer5678.spanish_page, None)

    def test_get_reusable_text_snippet(self):
        from ask_cfpb.models import get_reusable_text_snippet
        from v1.models.snippets import ReusableText

        test_snippet = ReusableText.objects.create(title="Test Snippet")
        self.assertEqual(
            get_reusable_text_snippet("Test Snippet"), test_snippet
        )

    def test_get_nonexistent_reusable_text_snippet(self):
        from ask_cfpb.models import get_reusable_text_snippet

        self.assertEqual(
            get_reusable_text_snippet("Nonexistent Snippet"), None
        )

    def test_get_about_us_english_standard_text(self):
        from ask_cfpb.models import get_standard_text
        from v1.models.snippets import ReusableText

        snippet_title = REUSABLE_TEXT_TITLES["about_us"]["en"]
        test_snippet = ReusableText.objects.create(title=snippet_title)
        self.assertEqual(get_standard_text("en", "about_us"), test_snippet)

    def test_social_sharing_image_used(self):
        from v1.models.images import CFGOVImage

        image = CFGOVImage.objects.last()
        page = self.page1
        page.social_sharing_image = image
        page.save_revision(user=self.test_user).publish()
        self.assertEqual(page.meta_image, image)

    def test_answer_meta_image_undefined(self):
        """ Answer page's meta image is undefined if social image is
        not provided
        """
        answer = Answer()
        answer.save()
        page = self.create_answer_page(answer_base=answer)
        self.assertIsNone(page.meta_image)

    def test_answer_meta_image_uses_category_image_if_no_social_image(self):
        """ Answer page's meta image is its category's image """
        category = baker.make(Category, category_image=self.test_image)
        page = self.page1
        page.category.add(category)
        page.save_revision()
        self.assertEqual(page.meta_image, self.test_image)

    def test_answer_split_testing_id(self):
        """Confirm AnswerPage's split_testing_id is set to its answer_base.id,
        which is checked by the core.feature_flags.in_split_testing_cluster
        flag condition when doing split testing on Ask CFPB answer pages."""
        answer = self.answer1234
        page = answer.english_page
        self.assertEqual(page.split_test_id, answer.id)

    def test_validate_pagination_number(self):
        paginator = Paginator([{"fake": "results"}] * 30, 25)
        request = HttpRequest()
        self.assertEqual(validate_page_number(request, paginator), 1)
        request.GET.update({"page": "2"})
        self.assertEqual(validate_page_number(request, paginator), 2)
        request = HttpRequest()
        request.GET.update({"page": "1000"})
        self.assertEqual(validate_page_number(request, paginator), 1)
        request = HttpRequest()
        request.GET.update({"page": "<script>Boo</script>"})
        self.assertEqual(validate_page_number(request, paginator), 1)
 def test_answer_string_method(self):
     test_answer = Answer(question="Test question?")
     test_answer.save()
     self.assertEqual(test_answer.__str__(), test_answer.question)
Beispiel #12
0
class AnswerPageTestCase(TestCase):

    fixtures = ['ask_tests', 'portal_topics']

    def create_answer_page(self, **kwargs):
        kwargs.setdefault('path', get_free_path(apps,
                                                self.english_parent_page))
        kwargs.setdefault('depth', self.english_parent_page.depth + 1)
        kwargs.setdefault('slug', 'mock-answer-page-en-1234')
        kwargs.setdefault('title', 'Mock answer page title')
        page = mommy.prepare(AnswerPage, **kwargs)
        page.save()
        return page

    def setUp(self):
        self.test_user = User.objects.get(pk=1)
        ROOT_PAGE = HomePage.objects.get(slug='cfgov')
        self.category = mommy.make(Category,
                                   name='stub_cat',
                                   name_es='que',
                                   slug='stub-cat')
        self.category.save()
        self.test_image = mommy.make(CFGOVImage)
        self.test_image2 = mommy.make(CFGOVImage)
        self.next_step = mommy.make(NextStep, title='stub_step')
        self.portal_topic = mommy.make(PortalTopic,
                                       heading='test topic',
                                       heading_es='prueba tema')
        page_clean = mock.patch('ask_cfpb.models.pages.CFGOVPage.clean')
        page_clean.start()
        self.addCleanup(page_clean.stop)
        self.portal_page = SublandingPage(title='test portal page',
                                          slug='test-portal-page',
                                          portal_topic=self.portal_topic,
                                          language='en')
        ROOT_PAGE.add_child(instance=self.portal_page)
        self.portal_page.save()
        self.portal_page.save_revision().publish()
        self.portal_page_es = SublandingPage(title='test portal page',
                                             slug='test-portal-page-es',
                                             portal_topic=self.portal_topic,
                                             language='es')
        ROOT_PAGE.add_child(instance=self.portal_page_es)
        self.portal_page_es.save()
        self.portal_page_es.save_revision().publish()
        self.english_parent_page = get_or_create_page(apps,
                                                      'ask_cfpb',
                                                      'AnswerLandingPage',
                                                      'Ask CFPB',
                                                      ENGLISH_PARENT_SLUG,
                                                      ROOT_PAGE,
                                                      language='en',
                                                      live=True)
        self.spanish_parent_page = get_or_create_page(apps,
                                                      'ask_cfpb',
                                                      'AnswerLandingPage',
                                                      'Obtener respuestas',
                                                      SPANISH_PARENT_SLUG,
                                                      ROOT_PAGE,
                                                      language='es',
                                                      live=True)
        self.tag_results_page_en = get_or_create_page(apps,
                                                      'ask_cfpb',
                                                      'TagResultsPage',
                                                      'Tag results page',
                                                      'search-by-tag',
                                                      ROOT_PAGE,
                                                      language='en',
                                                      live=True)
        self.tag_results_page_es = get_or_create_page(apps,
                                                      'ask_cfpb',
                                                      'TagResultsPage',
                                                      'Tag results page',
                                                      'buscar-por-etiqueta',
                                                      ROOT_PAGE,
                                                      language='es',
                                                      live=True)
        self.answer1234 = Answer(id=1234)
        self.answer1234.save()
        self.page1 = AnswerPage(language='en',
                                answer_base=self.answer1234,
                                slug='mock-question-en-1234',
                                title='Mock question1',
                                answer_content='Mock answer 1',
                                question='Mock question1',
                                search_tags='hippodrome')
        self.english_parent_page.add_child(instance=self.page1)
        self.page1.save_revision().publish()
        self.page1_es = AnswerPage(language='es',
                                   slug='mock-spanish-question1-es-1234',
                                   title='Mock Spanish question1',
                                   answer_base=self.answer1234,
                                   answer_content='Mock Spanish answer',
                                   question='Mock Spanish question1',
                                   search_tags='hipotecas')
        self.spanish_parent_page.add_child(instance=self.page1_es)
        self.page1_es.save_revision().publish()
        self.answer5678 = Answer(id=5678)
        self.answer5678.save()
        self.page2 = AnswerPage(language='en',
                                slug='mock-question2-en-5678',
                                title='Mock question2',
                                answer_base=self.answer5678,
                                answer_content='Mock answer 2',
                                question='Mock question2',
                                search_tags='hippodrome')
        self.english_parent_page.add_child(instance=self.page2)
        self.page2.save_revision().publish()

    def test_tag_results_page_templates(self):
        self.assertEqual(self.tag_results_page_es.get_template(HttpRequest()),
                         self.tag_results_page_en.get_template(HttpRequest()))

    def test_tag_results_page_context_language(self):
        context = self.tag_results_page_es.get_context(HttpRequest())
        self.assertEqual(
            context.get('breadcrumb_items')[0]['title'], 'Obtener respuestas')

    def test_get_answer_preview(self):
        """Check that get_answer_preview returns truncated text, no tags."""
        page = self.page1
        stream_data = [{
            'type': 'video_player',
            'id': '402b933b',
            'value': {
                'video_url': 'https://www.youtube.com/embed/wcQ1a_Gg8tI'
            }
        }, {
            'type': 'text',
            'id': '402b933c',
            'value': {
                'content':
                ('<p><span>'
                 'This is more than forty words: '
                 'word word word word word word word word word word '
                 'word word word word word word word word word word '
                 'word word word word word word word word word word '
                 'word word word word word word too-many.'
                 '</span></p>')
            }
        }]
        set_stream_data(page, 'answer_content', stream_data)
        self.assertTrue(get_answer_preview(page).endswith('word word ...'))

    def test_english_page_context(self):
        from v1.models.snippets import ReusableText
        from ask_cfpb.models.pages import get_reusable_text_snippet
        rt = ReusableText(title='About us (For consumers)')
        rt.save()
        page = self.page1
        page.language = 'en'
        page.save()
        test_context = page.get_context(HttpRequest())
        self.assertEqual(test_context['about_us'],
                         get_reusable_text_snippet('About us (For consumers)'))

    def test_english_page_sibling_url(self):
        self.assertEqual(self.page1.get_sibling_url(), self.page1_es.url)

    def test_spanish_page_sibling_url(self):
        self.assertEqual(self.page1_es.get_sibling_url(), self.page1.url)

    def test_no_sibling_url_returned_for_redirected_page(self):
        self.page1_es.redirect_to_page = self.page2
        self.page1_es.save()
        self.page1_es.save_revision(user=self.test_user).publish()
        self.assertEqual(self.page1.get_sibling_url(), None)

    def test_no_sibling_url_returned_for_draft_page(self):
        self.page1.unpublish()
        self.assertEqual(self.page1_es.get_sibling_url(), None)

    def test_routable_tag_page_base_returns_404(self):
        page = self.tag_results_page_en
        response = self.client.get(page.url + page.reverse_subpage('tag_base'))
        self.assertEqual(response.status_code, 404)

    def test_routable_tag_page_handles_bad_tag(self):
        page = self.tag_results_page_en
        response = self.client.get(
            page.url +
            page.reverse_subpage('tag_search', kwargs={'tag': 'hippopotamus'}))
        self.assertEqual(response.status_code, 200)

    def test_routable_tag_page_handles_bad_pagination(self):
        page = self.tag_results_page_en
        response = self.client.get(
            page.url +
            page.reverse_subpage('tag_search', kwargs={'tag': 'hippodrome'}),
            {'page': '100'})
        self.assertEqual(response.status_code, 200)

    def test_routable_tag_page_valid_tag_returns_200(self):
        page = self.tag_results_page_en
        response = self.client.get(
            page.url +
            page.reverse_subpage('tag_search', kwargs={'tag': 'hippodrome'}))
        self.assertEqual(response.status_code, 200)

    def test_routable_tag_page_returns_url_suffix(self):
        page = self.tag_results_page_en
        response = page.reverse_subpage('tag_search',
                                        kwargs={'tag': 'hippodrome'})
        self.assertEqual(response, 'hippodrome/')

    def test_view_answer_exact_slug(self):
        page = self.page1
        page.slug = 'mock-answer-en-1234'
        page.save()
        revision = page.save_revision()
        revision.publish()
        response = self.client.get(
            reverse('ask-english-answer', args=['mock-answer', 'en', 1234]))
        self.assertEqual(response.status_code, 200)

    def test_view_answer_301_for_healed_slug(self):
        page = self.page1
        revision = page.save_revision()
        revision.publish()
        response = self.client.get(
            reverse('ask-english-answer', args=['mock-slug', 'en', 1234]))
        self.assertEqual(response.status_code, 301)

    def test_view_answer_redirected(self):
        page = self.page1
        page.redirect_to = self.page2.answer_base
        page.save()
        revision = page.save_revision()
        revision.publish()
        response_302 = self.client.get(
            reverse('ask-english-answer',
                    args=['mocking-answer-page', 'en', 1234]))
        self.assertTrue(isinstance(response_302, HttpResponse))
        self.assertEqual(response_302.status_code, 301)

    def test_spanish_answer_page_handles_referrer_with_unicode_accents(self):
        referrer_unicode = (
            'https://www.consumerfinance.gov/es/obtener-respuestas/'
            'buscar-por-etiqueta/empresas_de_informes_de_cr\xe9dito/')
        spanish_page = self.page1_es
        request = HttpRequest()
        request.POST['referrer'] = referrer_unicode
        response = spanish_page.serve(request)
        self.assertEqual(response.status_code, 200)

    def test_page_string_no_base(self):
        test_page = self.create_answer_page()
        result = test_page.__str__()
        self.assertEqual(result, test_page.title)

    def test_page_string_with_base(self):
        page = self.page1
        self.assertTrue(page.answer_base)
        result = page.__str__()
        self.assertEqual(result, "{}: {}".format(page.answer_base.pk,
                                                 page.title))

    def test_search_tags(self):
        """Test the list produced by page.clean_search_tags()"""
        page = self.page1
        page.search_tags = 'Chutes, Ladders'
        page.save_revision().publish()
        taglist = page.clean_search_tags
        for name in ['Chutes', 'Ladders']:
            self.assertIn(name, taglist)

    def test_english_header_and_footer(self):
        english_answer_page_response = self.client.get(
            reverse('ask-english-answer', args=['mock-question', 'en', 1234]))
        self.assertContains(
            english_answer_page_response,
            'An official website of the United States government')
        self.assertNotContains(
            english_answer_page_response,
            'Un sitio web oficial del gobierno federal de los Estados Unidos')
        self.assertContains(english_answer_page_response, 'https://usa.gov/')
        self.assertNotContains(english_answer_page_response,
                               'https://gobiernousa.gov/')

    def test_spanish_header_and_footer(self):
        spanish_answer_page_response = self.client.get(
            reverse('ask-spanish-answer',
                    args=['mock-spanish-question1', 'es', 1234]))
        self.assertContains(
            spanish_answer_page_response,
            'Un sitio web oficial del gobierno federal de los Estados Unidos')
        self.assertNotContains(
            spanish_answer_page_response,
            'An official website of the United States government')
        self.assertContains(spanish_answer_page_response,
                            'https://gobiernousa.gov/')
        self.assertNotContains(spanish_answer_page_response,
                               'https://usa.gov/')

    def test_category_str(self):
        category = self.category
        self.assertEqual(category.__str__(), category.name)

    def test_portal_topic_featured_answers(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        self.assertIn(page, self.portal_topic.featured_answers('en'))

    def test_nextstep_str(self):
        next_step = self.next_step
        self.assertEqual(next_step.__str__(), next_step.title)

    def test_status_string(self):
        with translation.override('en'):
            page1 = self.page1
            self.assertEqual((page1.status_string), 'live + draft')

    def test_status_string_redirected(self):
        with translation.override('en'):
            page1 = self.page1
            page1.redirect_to_page = self.page2
            page1.save()
            page1.get_latest_revision().publish()
            self.assertEqual((page1.status_string), "redirected")
            page1.unpublish()
            self.assertEqual(page1.status_string, ("redirected but not live"))

    def test_get_ask_breadcrumbs(self):
        from ask_cfpb.models import get_ask_breadcrumbs
        breadcrumbs = get_ask_breadcrumbs()
        self.assertEqual(len(breadcrumbs), 1)
        self.assertEqual(breadcrumbs[0]['title'], 'Ask CFPB')

    def test_landing_page_context_no_featured_answer(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = False
        page.save_revision().publish()
        mock_site = mock.Mock()
        mock_site.hostname = 'localhost'
        mock_request = HttpRequest()
        mock_request.site = mock_site
        landing_page = self.english_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context['portal_cards']), 0)

    def test_landing_page_context(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        mock_site = mock.Mock()
        mock_site.hostname = 'localhost'
        mock_request = HttpRequest()
        mock_request.site = mock_site
        landing_page = self.english_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context['portal_cards']), 1)
        self.assertEqual(test_context['portal_cards'][0]['title'],
                         'test topic')

    def test_spanish_landing_page_context(self):
        page = self.page1_es
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        mock_site = mock.Mock()
        mock_site.hostname = 'localhost'
        mock_request = HttpRequest()
        mock_request.site = mock_site
        landing_page = self.spanish_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context['portal_cards']), 1)
        self.assertEqual(test_context['portal_cards'][0]['title'],
                         'prueba tema')

    def test_landing_page_context_draft_portal_page(self):
        page = self.page1
        page.portal_topic.add(self.portal_topic)
        page.featured = True
        page.save_revision().publish()
        self.portal_page.unpublish()
        mock_site = mock.Mock()
        mock_site.hostname = 'localhost'
        mock_request = HttpRequest()
        mock_request.site = mock_site
        landing_page = self.english_parent_page
        test_context = landing_page.get_context(mock_request)
        self.assertEqual(len(test_context['portal_cards']), 0)

    def test_answer_language_page_exists(self):
        self.assertEqual(self.answer5678.english_page, self.page2)

    def test_answer_language_page_nonexistent(self):
        self.assertEqual(self.answer5678.spanish_page, None)

    def test_get_reusable_text_snippet(self):
        from ask_cfpb.models import get_reusable_text_snippet
        from v1.models.snippets import ReusableText
        test_snippet = ReusableText.objects.create(title='Test Snippet')
        self.assertEqual(get_reusable_text_snippet('Test Snippet'),
                         test_snippet)

    def test_get_nonexistent_reusable_text_snippet(self):
        from ask_cfpb.models import get_reusable_text_snippet
        self.assertEqual(get_reusable_text_snippet('Nonexistent Snippet'),
                         None)

    def test_get_about_us_english_standard_text(self):
        from ask_cfpb.models import get_standard_text
        from v1.models.snippets import ReusableText
        snippet_title = REUSABLE_TEXT_TITLES['about_us']['en']
        test_snippet = ReusableText.objects.create(title=snippet_title)
        self.assertEqual(get_standard_text('en', 'about_us'), test_snippet)

    def test_social_sharing_image_used(self):
        from v1.models.images import CFGOVImage
        image = CFGOVImage.objects.last()
        page = self.page1
        page.social_sharing_image = image
        page.save_revision(user=self.test_user).publish()
        self.assertEqual(page.meta_image, image)

    def test_answer_meta_image_undefined(self):
        """ Answer page's meta image is undefined if social image is
        not provided
        """
        answer = Answer()
        answer.save()
        page = self.create_answer_page(answer_base=answer)
        self.assertIsNone(page.meta_image)

    def test_answer_meta_image_uses_category_image_if_no_social_image(self):
        """ Answer page's meta image is its category's image """
        category = mommy.make(Category, category_image=self.test_image)
        page = self.page1
        page.category.add(category)
        page.save_revision()
        self.assertEqual(page.meta_image, self.test_image)

    def test_answer_split_testing_id(self):
        """Confirm AnswerPage's split_testing_id is set to its answer_base.id,
        which is checked by the core.feature_flags.in_split_testing_cluster
        flag condition when doing split testing on Ask CFPB answer pages."""
        answer = self.answer1234
        page = answer.english_page
        self.assertEqual(page.split_test_id, answer.id)

    def test_validate_pagination_number(self):
        paginator = Paginator([{'fake': 'results'}] * 30, 25)
        request = HttpRequest()
        self.assertEqual(validate_page_number(request, paginator), 1)
        request.GET.update({'page': '2'})
        self.assertEqual(validate_page_number(request, paginator), 2)
        request = HttpRequest()
        request.GET.update({'page': '1000'})
        self.assertEqual(validate_page_number(request, paginator), 1)
        request = HttpRequest()
        request.GET.update({'page': '<script>Boo</script>'})
        self.assertEqual(validate_page_number(request, paginator), 1)

    def test_schema_html_does_not_appear_when_flag_is_off(self):
        with override_settings(FLAGS={'HOW_TO_SCHEMA': [('boolean', False)]}):
            response = self.client.get(self.page1.url)
            self.assertNotContains(response,
                                   'itemtype="http://schema.org/HowTo"')

    def test_schema_html_appears_when_flag_is_on(self):
        with override_settings(FLAGS={'HOW_TO_SCHEMA': [('boolean', True)]}):
            response = self.client.get(self.page1.url)
            self.assertContains(response, 'itemtype="http://schema.org/HowTo"')
class AnswerPageDocumentTest(TestCase):
    def setUp(self):
        self.site = Site.objects.get(is_default_site=True)
        self.root_page = self.site.root_page
        self.portal_topic = baker.make(PortalTopic,
                                       heading="test topic",
                                       heading_es="prueba tema")
        self.en_portal_category = baker.make(PortalCategory,
                                             heading="test_english_heading")
        self.es_portal_category = baker.make(PortalCategory,
                                             heading="test_spanish_heading")
        self.en_portal_page = SublandingPage(
            title="test English portal page",
            slug="test-en-portal-page",
            portal_topic=self.portal_topic,
            language="en",
        )
        self.es_portal_page = SublandingPage(
            title="test Spanish portal page",
            slug="test-es-portal-page",
            portal_topic=self.portal_topic,
            language="es",
        )
        self.root_page.add_child(instance=self.en_portal_page)
        self.en_portal_page.save()
        self.en_portal_page.save_revision().publish()
        self.en_parent_page = get_or_create_page(
            apps,
            "ask_cfpb",
            "AnswerLandingPage",
            "Ask CFPB",
            ENGLISH_PARENT_SLUG,
            self.root_page,
            language="en",
            live=True,
        )
        self.es_parent_page = get_or_create_page(
            apps,
            "ask_cfpb",
            "AnswerLandingPage",
            "Obtener respuestas",
            SPANISH_PARENT_SLUG,
            self.root_page,
            language="es",
            live=True,
        )
        self.answer = Answer(id=1234)
        self.answer.save()
        self.en_page = AnswerPage(
            language="en",
            slug="test-english-question-en-1234",
            title="Test English question",
            answer_base=self.answer,
            answer_content="Test English answer",
            question="Test English question",
            search_tags="English",
        )
        self.es_page = AnswerPage(
            language="es",
            slug="test-spanish-question-es-1234",
            title="Test Spanish question",
            answer_base=self.answer,
            answer_content="Test Spanish answer",
            question="Test Spanish question",
            search_tags="Spanish",
        )
        self.doc = AnswerPageDocument()

    def test_model_class_added(self):
        self.assertEqual(AnswerPageDocument.django.model, AnswerPage)

    def test_ignore_signal_default(self):
        self.assertFalse(AnswerPageDocument.django.ignore_signals)

    def test_auto_refresh_default(self):
        self.assertFalse(AnswerPageDocument.django.auto_refresh)

    def test_fields_populated(self):
        mapping = AnswerPageDocument._doc_type.mapping
        self.assertEqual(
            set(mapping.properties.properties.to_dict().keys()),
            set([
                'autocomplete', 'portal_categories', 'portal_topics', 'text',
                'url', 'preview', 'search_tags', 'language'
            ]))

    def test_to_field(self):
        doc = DocType()
        for f in ['question', 'statement']:
            nameField = doc.to_field(f, AnswerPage._meta.get_field(f))
            self.assertIsInstance(nameField, fields.TextField)
            self.assertEqual(nameField._path, [f])
        dateField = doc.to_field('last_edited',
                                 AnswerPage._meta.get_field('last_edited'))
        self.assertIsInstance(dateField, fields.DateField)
        self.assertEqual(dateField._path, ['last_edited'])
        for f in ['featured', 'share_and_print']:
            boolField = doc.to_field(f, AnswerPage._meta.get_field(f))
            self.assertIsInstance(boolField, fields.BooleanField)
            self.assertEqual(boolField._path, [f])
        intField = doc.to_field('featured_rank',
                                AnswerPage._meta.get_field('featured_rank'))
        self.assertIsInstance(intField, fields.IntegerField)
        self.assertEqual(intField._path, ['featured_rank'])

    def test_to_field_with_unknown_field(self):
        doc = DocType()
        with self.assertRaises(ModelFieldNotMappedError):
            doc.to_field('answer_base',
                         AnswerPage._meta.get_field('answer_base'))

    def test_mapping(self):
        self.assertEqual(
            AnswerPageDocument._doc_type.mapping.to_dict(), {
                'properties': {
                    'autocomplete': {
                        'analyzer': 'ngram_tokenizer',
                        'type': 'text'
                    },
                    'language': {
                        'type': 'text'
                    },
                    'portal_categories': {
                        'type': 'text'
                    },
                    'portal_topics': {
                        'type': 'keyword'
                    },
                    'preview': {
                        'type': 'text'
                    },
                    'search_tags': {
                        'type': 'text'
                    },
                    'text': {
                        'analyzer': 'synonym_analyzer',
                        'type': 'text'
                    },
                    'url': {
                        'type': 'text'
                    }
                }
            })

    def test_get_queryset(self):
        qs = AnswerPageDocument().get_queryset()
        self.assertIsInstance(qs, models.QuerySet)
        self.assertEqual(qs.model, AnswerPage)

    def test_prepare_en(self):
        self.en_parent_page.add_child(instance=self.en_page)
        self.en_page.save_revision().publish()
        en_prepared_data = self.doc.prepare(self.en_page)
        self.assertEqual(
            en_prepared_data, {
                'autocomplete':
                self.doc.prepare_autocomplete(self.en_page),
                'language':
                'en',
                'portal_categories':
                self.doc.prepare_portal_categories(self.en_page),
                'portal_topics':
                self.doc.prepare_portal_topics(self.en_page),
                'preview':
                '',
                'search_tags':
                self.doc.prepare_search_tags(self.en_page),
                'text':
                'Test English question\n\n\n\n',
                'url':
                self.doc.prepare_url(self.en_page),
            })

    def test_prepare_es(self):
        self.es_parent_page.add_child(instance=self.es_page)
        self.es_page.save_revision().publish()
        es_prepared_data = self.doc.prepare(self.es_page)
        self.assertEqual(
            es_prepared_data, {
                'autocomplete':
                self.doc.prepare_autocomplete(self.es_page),
                'language':
                'es',
                'portal_categories':
                self.doc.prepare_portal_categories(self.es_page),
                'portal_topics':
                self.doc.prepare_portal_topics(self.es_page),
                'preview':
                '',
                'search_tags':
                self.doc.prepare_search_tags(self.es_page),
                'text':
                'Test Spanish question\n\n\n\n',
                'url':
                self.doc.prepare_url(self.es_page),
            })

    def test_model_instance_update_no_refresh(self):
        self.es_parent_page.add_child(instance=self.es_page)
        self.es_page.save_revision().publish()
        self.doc.django.auto_refresh = False
        with patch('django_elasticsearch_dsl.documents.bulk') as mock:
            self.doc.update(self.es_page)
            self.assertNotIn('refresh', mock.call_args_list[0][1])