Example #1
0
    def test_good_visit_count(self):
        """Extract visit counts from good data.

        It has some nasty non-ASCII chars in it.

        """
        d = document(slug="hellỗ")
        d.save()
        d2 = document(slug="there")
        d2.save()
        # We get a str, not a unicode obj, out of the urllib call.
        eq_(
            {d.pk: 1037639, d2.pk: 213817},
            WikiDocumentVisits._visit_counts(
                '{"data": {"12/01/2010-12/07/2010": {"SubRows":{'
                '"http://support.mozilla.com/%s/kb/hellỗ":{"Attributes":{"Title":'
                '"Firefox Support Home Page | Firefox Support","UrlLink":'
                '"http://support.mozilla.com/en-US/home/"},"measures":'
                '{"Visits":1037639.0,"Views":3357731.0,"Average Time Viewed":23.0'
                '},"SubRows":null},"http://support.mozilla.com/%s/kb/there":'
                '{"Attributes":{"Title":"Startseite der Firefox-Hilfe | Firefox'
                'Support","UrlLink":"http://support.mozilla.com/de/home/"},'
                '"measures":{"Visits":213817.0,"Views":595329.0,"Average Time '
                'Viewed":25.0},"SubRows":null}}}}}' % ((settings.LANGUAGE_CODE,) * 2)
            ),
        )
Example #2
0
    def test_deferred_translation(self):
        """Verify a translation with only a deferred revision appears."""
        d = document(title='Foo', save=True)
        untranslated = revision(is_approved=True,
                                is_ready_for_localization=True,
                                document=d,
                                save=True)

        # There should be 1.
        eq_(1, len(self.titles(locale='es')))

        translation = document(
            parent=untranslated.document, locale='es', save=True)
        deferred = revision(is_approved=False,
                            reviewed=datetime.now(),
                            document=translation,
                            save=True)

        # There should still be 1.
        eq_(1, len(self.titles(locale='es')))

        # Mark that rev as approved and there should then be 0.
        deferred.is_approved = True
        deferred.save()
        eq_(0, len(self.titles(locale='es')))
Example #3
0
    def test_old_revisions(self):
        """Bug 862436. Updating old revisions could cause bad WLH data."""
        d1 = document(title='D1', save=True)
        revision(document=d1, content='', is_approved=True, save=True)
        d2 = document(title='D2', save=True)
        revision(document=d2, content='', is_approved=True, save=True)

        # Make D3, then make a revision that links to D1, then a
        # revision that links to D2. Only the link to D2 should count.
        d3 = document(title='D3', save=True)
        r3_old = revision(document=d3, content='[[D1]]', is_approved=True,
                          save=True)
        r3_new = revision(document=d3, content='[[D2]]', is_approved=True,
                          save=True)

        # This could cause stale data
        r3_old.content_parsed

        # D1 is not linked to in any current revisions.
        eq_(len(d1.links_to()), 0)
        eq_(len(d1.links_from()), 0)
        eq_(len(d2.links_to()), 1)
        eq_(len(d2.links_from()), 0)
        eq_(len(d3.links_to()), 0)
        eq_(len(d3.links_from()), 1)
Example #4
0
    def test_category_inheritance(self):
        """A document's categories must always be those of its parent."""
        some_category = CATEGORIES[1][0]
        other_category = CATEGORIES[0][0]

        # Notice if somebody ever changes the default on the category field,
        # which would invalidate our test:
        assert some_category != document().category

        parent = document(category=some_category)
        parent.save()
        child = document(parent=parent, locale='de')
        child.save()

        # Make sure child sees stuff set on parent:
        eq_(some_category, child.category)

        # Child'd category should revert to parent's on save:
        child.category = other_category
        child.save()
        eq_(some_category, child.category)

        # Changing the parent category should change the child's:
        parent.category = other_category

        parent.save()
        eq_(other_category,
            parent.translations.get(locale=child.locale).category)
Example #5
0
    def test_wiki_topics(self):
        """Search wiki for topics, includes multiple."""
        t1 = topic(slug='doesnotexist', save=True)
        t2 = topic(slug='extant', save=True)
        t3 = topic(slug='tagged', save=True)

        doc = document(locale=u'en-US', category=10, save=True)
        doc.topics.add(t2)
        revision(document=doc, is_approved=True, save=True)

        doc = document(locale=u'en-US', category=10, save=True)
        doc.topics.add(t2)
        doc.topics.add(t3)
        revision(document=doc, is_approved=True, save=True)

        self.refresh()

        topic_vals = (
            (t1.slug, 0),
            (t2.slug, 2),
            (t3.slug, 1),
            ([t2.slug, t3.slug], 1),
        )

        qs = {'a': 1, 'w': 1, 'format': 'json'}
        for topics, number in topic_vals:
            qs.update({'topics': topics})
            response = self.client.get(reverse('search'), qs)
            eq_(number, json.loads(response.content)['total'])
Example #6
0
    def test_search_suggestions_archived_articles(self):
        """Verifies that archived articles aren't shown."""
        topic(title='Fix problems', slug='fix-problems', save=True)
        p = product(slug=u'firefox', save=True)

        d1 = document(title=u'document donut', category=10, save=True)
        d1.products.add(p)
        revision(document=d1, is_approved=True, save=True)

        d2 = document(title=u'document cupcake', category=10, is_archived=True,
                      save=True)
        d2.products.add(p)
        revision(document=d1, is_approved=True, save=True)

        self.refresh()

        url = urlparams(
            reverse('questions.aaq_step4', args=['desktop', 'fix-problems']),
            search='document')

        response = self.client.get(url, follow=True)
        eq_(200, response.status_code)

        doc = pq(response.content)
        eq_(len(doc('.result.document')), 1)
        assert 'donut' in doc('.result.document h3 a').text()
        assert 'cupcake' not in doc('.result.document h3 a').text()
Example #7
0
 def _create_en_and_de_docs(self):
     en = settings.WIKI_DEFAULT_LANGUAGE
     en_doc = document(locale=en, slug='english-slug')
     en_doc.save()
     de_doc = document(locale='de', parent=en_doc)
     de_doc.save()
     de_rev = revision(document=de_doc, is_approved=True)
     de_rev.save()
     return en_doc, de_doc
Example #8
0
    def test_update_l10n_metric_cron(self):
        """Verify the cron job creates the correct metric."""
        l10n_kind = metric_kind(code=L10N_METRIC_CODE, save=True)

        # Create the en-US document with an approved revision.
        doc = document(save=True)
        rev = revision(
            document=doc,
            is_approved=True,
            save=True)

        time.sleep(1)

        # Create an es translation
        es_doc = document(parent=doc, locale='es', save=True)
        revision(
            document=es_doc,
            is_approved=True,
            based_on=rev,
            save=True)

        # Run it and verify results.
        # Value should be 100%
        update_l10n_metric()
        metrics = Metric.objects.filter(kind=l10n_kind)
        eq_(1, len(metrics))
        eq_(100, metrics[0].value)

        # Update the en-US document
        rev2 = revision(
            document=doc,
            is_approved=True,
            save=True)

        # Run it and verify results.
        # Value should be 0%
        update_l10n_metric()
        metrics = Metric.objects.filter(kind=l10n_kind)
        eq_(1, len(metrics))
        eq_(0, metrics[0].value)

        time.sleep(1)

        # Create a pt-BR translation
        ptBR_doc = document(parent=doc, locale='pt-BR', save=True)
        revision(
            document=ptBR_doc,
            is_approved=True,
            based_on=rev,
            save=True)

        # Run it and verify results.
        # Value should be 50%
        update_l10n_metric()
        metrics = Metric.objects.filter(kind=l10n_kind)
        eq_(1, len(metrics))
        eq_(50, metrics[0].value)
Example #9
0
    def test_only_localizable_allowed_children(self):
        """You can't have children for a non-localizable document."""
        # Make English rev:
        en_doc = document(is_localizable=False)
        en_doc.save()

        # Make Deutsch translation:
        de_doc = document(parent=en_doc, locale='de')
        self.assertRaises(ValidationError, de_doc.save)
Example #10
0
    def test_what_links_here(self):
        d1 = document(title='D1', save=True)
        revision(document=d1, content='', is_approved=True, save=True)
        d2 = document(title='D2', save=True)
        revision(document=d2, content='[[D1]]', is_approved=True, save=True)

        url = reverse('wiki.what_links_here', args=[d1.slug])
        resp = self.client.get(url, follow=True)
        eq_(200, resp.status_code)
        assert 'D2' in resp.content
Example #11
0
 def test_indirect_recursion(self):
     """Make sure indirect recursion is caught."""
     boo = document(title="Template:Boo")
     boo.save()
     yah = document(title="Template:Yah")
     yah.save()
     revision(document=boo, content="Paper [[Template:Yah]] Cups", is_approved=True).save()
     revision(document=yah, content="Wooden [[Template:Boo]] Bats", is_approved=True).save()
     recursion_message = RECURSION_MESSAGE % "Template:Boo"
     eq_("<p>Paper Wooden %s Bats\n Cups\n</p>" % recursion_message, boo.content_parsed)
Example #12
0
    def test_what_links_here_locale_filtering(self):
        d1 = document(title='D1', save=True, locale='de')
        revision(document=d1, content='', is_approved=True, save=True)
        d2 = document(title='D2', save=True, locale='fr')
        revision(document=d2, content='[[D1]]', is_approved=True, save=True)

        url = reverse('wiki.what_links_here', args=[d1.slug], locale='de')
        resp = self.client.get(url, follow=True)
        eq_(200, resp.status_code)
        assert 'No other documents link to D1.' in resp.content
Example #13
0
    def test_cannot_make_non_localizable_if_children(self):
        """You can't make a document non-localizable if it has children."""
        # Make English rev:
        en_doc = document(is_localizable=True)
        en_doc.save()

        # Make Deutsch translation:
        de_doc = document(parent=en_doc, locale='de')
        de_doc.save()
        en_doc.is_localizable = False
        self.assertRaises(ValidationError, en_doc.save)
Example #14
0
 def test_new_doc_does_not_update_categories(self):
     """Make sure that creating a new document doesn't change the
     category of all the other documents."""
     d1 = document(category=10)
     d1.save()
     assert d1.pk
     d2 = document(category=00)
     assert not d2.pk
     d2._clean_category()
     d1prime = Document.objects.get(pk=d1.pk)
     eq_(10, d1prime.category)
Example #15
0
    def test_get_products(self):
        """Test the get_products() method."""
        en_us = document(save=True)
        en_us.products.add(product(save=True))
        en_us.products.add(product(save=True))

        eq_(2, len(en_us.get_products()))

        # Localized document inherits parent's topics.
        l10n = document(parent=en_us, save=True)
        eq_(2, len(en_us.get_products()))
Example #16
0
 def test_template_locale(self):
     """Localized template is returned."""
     py_doc, p = doc_parse_markup('English content', '[[Template:test]]')
     parent = document()
     d = document(parent=parent, title='Template:test', locale='fr')
     d.save()
     r = revision(content='French content', document=d, is_approved=True)
     r.save()
     eq_('English content', py_doc.text())
     py_doc = pq(p.parse('[[T:test]]', locale='fr'))
     eq_('French content', py_doc.text())
Example #17
0
 def test_template_locale(self):
     """Localized template is returned."""
     py_doc, p = doc_parse_markup("English content", "[[Template:test]]")
     parent = document()
     d = document(parent=parent, title="Template:test", locale="fr")
     d.save()
     r = revision(content="French content", document=d, is_approved=True)
     r.save()
     eq_("English content", py_doc.text())
     py_doc = pq(p.parse("[[T:test]]", locale="fr"))
     eq_("French content", py_doc.text())
Example #18
0
    def test_redirect_to_translated_document(self):
        from_url = Document.from_url

        d_en = document(locale="en-US", title=u"How to delete Google Chrome?", save=True)
        d_tr = document(locale="tr", title=u"Google Chrome'u nasıl silerim?", parent=d_en, save=True)
        # The /tr/kb/how-to-delete-google-chrome URL for Turkish locale
        # should be redirected to /tr/kb/google-chromeu-nasl-silerim
        # if there is a Turkish translation of the document.
        tr_translate_url = reverse("wiki.document", locale="tr", args=[d_en.slug])
        self.assertEqual(d_en.translated_to("tr"), from_url(tr_translate_url))
        self.assertEqual(d_tr, from_url(tr_translate_url))
        self.assertEqual(d_en, from_url(d_en.get_absolute_url()))
Example #19
0
    def test_topical_parents(self):
        d1 = document(title='HTML7')
        d1.save()

        d2 = document(title='Smellovision')
        d2.parent_topic = d1
        d2.save()
        ok_(d2.parents == [d1])

        d3 = document(title='Smell accessibility')
        d3.parent_topic = d2
        d3.save()
        ok_(d3.parents == [d1, d2])
Example #20
0
    def test_kb_vote(self):
        """Test vote API call."""
        r1 = revision(document=document(locale='en-US', save=True), save=True)
        r2 = revision(document=document(locale='es', save=True), save=True)
        for r in [r1, r2]:
            helpful_vote(revision=r, save=True)
            helpful_vote(revision=r, save=True)
            helpful_vote(revision=r, helpful=True, save=True)

        # Only the votes for r1 (locale=en-US) should be counted.
        r = self._get_api_result('kpi_kb_vote')
        eq_(r['objects'][0]['kb_helpful'], 1)
        eq_(r['objects'][0]['kb_votes'], 3)
Example #21
0
    def test_redirect_nondefault_locales(self):
        title1 = "title1"
        title2 = "title2"

        redirect_to = revision(document=document(title=title1, locale="es", save=True), is_approved=True, save=True)

        redirector = revision(
            document=document(title=title2, locale="es", save=True),
            content=u"REDIRECT [[%s]]" % redirect_to.document.title,
            is_approved=True,
            save=True,
        )

        eq_(redirect_to.document.get_absolute_url(), redirector.document.redirect_url())
Example #22
0
    def test_wiki_topics_inherit(self):
        """Translations inherit topics from their parents."""
        doc = document(locale=u"en-US", category=10, save=True)
        doc.topics.add(topic(slug="extant", save=True))
        revision(document=doc, is_approved=True, save=True)

        translated = document(locale=u"es", parent=doc, category=10, save=True)
        revision(document=translated, is_approved=True, save=True)

        self.refresh()

        qs = {"a": 1, "w": 1, "format": "json", "topics": "extant"}
        response = self.client.get(reverse("search", locale="es"), qs)
        eq_(1, json.loads(response.content)["total"])
Example #23
0
    def _test_collision_avoidance(self, attr, other_attr, template):
        """When creating redirects, dodge existing docs' titles and slugs."""
        # Create a doc called something like Whatever Redirect 1:
        document(
            locale=self.d.locale, **{other_attr: template % dict(old=getattr(self.d, other_attr), number=1)}
        ).save()

        # Trigger creation of a redirect of a new title or slug:
        setattr(self.d, attr, "new")
        self.d.save()

        # It should be called something like Whatever Redirect 2:
        redirect = Document.uncached.get(**{attr: getattr(self, "old_" + attr)})
        eq_(template % dict(old=getattr(self.d, other_attr), number=2), getattr(redirect, other_attr))
Example #24
0
    def test_wiki_products_inherit(self):
        """Translations inherit products from their parents."""
        doc = document(locale=u"en-US", category=10, save=True)
        p = product(title=u"Firefox", slug=u"desktop", save=True)
        doc.products.add(p)
        revision(document=doc, is_approved=True, save=True)

        translated = document(locale=u"fr", parent=doc, category=10, save=True)
        revision(document=translated, is_approved=True, save=True)

        self.refresh()

        qs = {"a": 1, "w": 1, "format": "json", "product": p.slug}
        response = self.client.get(reverse("search", locale="fr"), qs)
        eq_(1, json.loads(response.content)["total"])
Example #25
0
    def test_products_inherit(self):
        """Translations inherit products from their parents."""
        doc = document(locale=u'en-US', category=10, save=True)
        doc.tags.add(u'desktop')
        revision(document=doc, is_approved=True, save=True)

        translated = document(locale=u'fr', parent=doc, category=10,
                              save=True)
        revision(document=translated, is_approved=True, save=True)

        self.refresh()

        qs = {'a': 1, 'w': 1, 'format': 'json', 'product': 'desktop'}
        response = self.client.get(reverse('search', locale='fr'), qs)
        eq_(1, json.loads(response.content)['total'])
Example #26
0
    def test_inheritance(self):
        """Make sure parent/child equality of is_archived is maintained."""
        # Set up a child and a parent and an orphan (all false) and something
        # true.
        translated_revision(save=True)
        translated_revision(save=True)
        document(save=True)
        document(is_archived=True, save=True)

        # Batch-clear the archival bits:
        DocumentAdmin._set_archival(Document.objects.all(), True)

        # Assert the child of the parent and the parent of the child (along
        # with everything else) became (or stayed) true:
        eq_(Document.objects.filter(is_archived=True).count(), 6)
Example #27
0
    def test_wiki_topics_inherit(self):
        """Translations inherit topics from their parents."""
        doc = document(locale=u'en-US', category=10, save=True)
        doc.topics.add(topic(slug='extant', save=True))
        revision(document=doc, is_approved=True, save=True)

        translated = document(locale=u'es', parent=doc, category=10,
                              save=True)
        revision(document=translated, is_approved=True, save=True)

        self.refresh()

        qs = {'a': 1, 'w': 1, 'format': 'json', 'topics': 'extant'}
        response = self.client.get(reverse('search', locale='es'), qs)
        eq_(1, json.loads(response.content)['total'])
Example #28
0
    def test_advanced_search_for_wiki_no_query(self):
        """Tests advanced search with no query"""
        doc = document(
            title=u'How to fix your audio',
            locale=u'en-US',
            category=10)
        doc.save()

        doc.tags.add(u'desktop')

        rev = revision(
            document=doc,
            summary=u'Volume.',
            content=u'Turn up the volume.',
            is_approved=True)
        rev.save()

        self.refresh()

        # This is the search that you get when you start on the sumo
        # homepage and do a search from the box with two differences:
        # first, we do it in json since it's easier to deal with
        # testing-wise and second, we search for 'audio' since we have
        # data for that.
        response = self.localizing_client.get(reverse('search'), {
            'q': '', 'tags': 'desktop', 'w': '1', 'a': '1',
            'format': 'json'
        })

        eq_(200, response.status_code)

        content = json.loads(response.content)
        eq_(content['total'], 1)
Example #29
0
    def test_majorly_outdated_with_unapproved_parents(self):
        """Migrations might introduce translated revisions without based_on
        set. Tolerate these.

        If based_on of a translation's current_revision is None, the
        translation should be considered out of date iff any
        major-significance, approved revision to the English article exists.

        """
        # Create a parent doc with only an unapproved revision...
        parent_rev = revision()
        parent_rev.save()
        # ...and a translation with a revision based on nothing.
        trans = document(parent=parent_rev.document, locale='de')
        trans.save()
        trans_rev = revision(document=trans, is_approved=True)
        trans_rev.save()

        assert trans_rev.based_on is None, \
            ('based_on defaulted to something non-None, which this test '
             "wasn't expecting.")

        assert not trans.is_majorly_outdated(), \
            ('A translation was considered majorly out of date even though '
             'the English document has never had an approved revision of '
             'major significance.')

        major_parent_rev = revision(document=parent_rev.document,
                                    significance=MAJOR_SIGNIFICANCE,
                                    is_approved=True)
        major_parent_rev.save()

        assert trans.is_majorly_outdated(), \
            ('A translation was not considered majorly outdated when its '
             "current revision's based_on value was None.")
Example #30
0
 def test_unlocalizable(self):
     """Unlocalizable docs shouldn't show up in the list."""
     revision(
         document=document(is_localizable=False, save=True),
         is_approved=True,
         save=True)
     self.assertRaises(IndexError, self.row)
Example #31
0
    def test_link_with_localization(self):
        """A link to an English doc with a local translation."""
        en_d = document(title='A doc')
        en_d.save()
        en_r = revision(document=en_d, is_approved=True)
        en_r.save()

        fr_d = document(parent=en_d, title='Une doc', locale='fr')
        fr_d.save()

        # Without an approved revision, link should go to en-US doc.
        # The site should stay in fr locale (/<locale>/<en-US slug>).
        link = pq(self.p.parse('[[A doc]]', locale='fr'))
        eq_('/fr/kb/a-doc', link.find('a').attr('href'))
        eq_('A doc', link.find('a').text())

        # Approve a revision. Now link should go to fr doc.
        fr_r = revision(document=fr_d, is_approved=True)
        fr_r.save()
        link = pq(self.p.parse('[[A doc]]', locale='fr'))
        eq_('/fr/kb/une-doc', link.find('a').attr('href'))
        eq_('Une doc', link.find('a').text())
Example #32
0
    def test_by_product(self):
        """Test the product filtering of the readout."""
        locale = settings.WIKI_DEFAULT_LANGUAGE
        p = product(title='Firefox', slug='firefox', save=True)
        d = document(save=True)
        r = revision(document=d, is_approved=True, save=True)

        # There shouldn't be any rows yet.
        eq_(0, len(self.rows(locale=locale, product=p)))

        # Add the product to the document, and verify it shows up.
        d.products.add(p)
        eq_(self.row(locale=locale, product=p)['title'], d.title)
Example #33
0
    def test_direct_recursion(self):
        """Make sure direct recursion is caught on the very first nesting."""
        d = document(title='Boo')
        d.save()

        # Twice so the second revision sees content identical to itself:
        for i in range(2):
            revision(document=d,
                     content='Fine [[Include:Boo]] Fellows',
                     is_approved=True).save()

        eq_('<p>Fine %s Fellows\n</p>' % (RECURSION_MESSAGE % 'Boo'),
            d.content_parsed)
Example #34
0
    def _test_int_sets_and_descriptors(self, enum_class, attr):
        """Test our lightweight int sets & descriptors' getting and setting."""
        d = document()
        d.save()
        _objects_eq(getattr(d, attr), [])

        i1 = enum_class(item_id=1)
        getattr(d, attr).add(i1)
        _objects_eq(getattr(d, attr), [i1])

        i2 = enum_class(item_id=2)
        getattr(d, attr).add(i2)
        _objects_eq(getattr(d, attr), [i1, i2])
Example #35
0
 def test_for_in_template(self):
     """Verify that {for}'s render correctly in template."""
     d = document(title='Template:for')
     d.save()
     r = revision(document=d,
                  content='{for win}windows{/for}{for mac}mac{/for}')
     r.is_approved = True
     r.save()
     p = WikiParser()
     content = p.parse('[[Template:for]]')
     eq_(
         '<p><span class="for" data-for="win">windows</span>'
         '<span class="for" data-for="mac">mac</span>\n\n</p>', content)
Example #36
0
    def test_translations_get_parent_tags(self):
        doc1 = document(title=u'Audio too loud')
        doc1.save()
        revision(document=doc1, is_approved=True, save=True)
        doc1.topics.add(topic(slug='cookies', save=True))
        doc1.topics.add(topic(slug='general', save=True))
        doc1.products.add(product(slug='desktop', save=True))

        doc2 = document(title=u'Audio too loud bork bork', parent=doc1)
        doc2.save()
        revision(document=doc2, is_approved=True, save=True)
        doc2.tags.add(u'badtag')

        # Verify the parent has the right tags.
        doc_dict = Document.extract_document(doc1.id)
        eq_(doc_dict['document_topic'], [u'cookies', u'general'])
        eq_(doc_dict['document_product'], [u'desktop'])

        # Verify the translation has the parent's tags.
        doc_dict = Document.extract_document(doc2.id)
        eq_(doc_dict['document_topic'], [u'cookies', u'general'])
        eq_(doc_dict['document_product'], [u'desktop'])
Example #37
0
    def test_revisions_feed(self):
        d = document(title='HTML9')
        d.save()
        now = datetime.datetime.now()
        for i in xrange(1, 6):
            created = now + datetime.timedelta(seconds=5 * i)
            revision(save=True,
                     document=d,
                     title='HTML9',
                     comment='Revision %s' % i,
                     content="Some Content %s" % i,
                     is_approved=True,
                     created=created)

        resp = self.client.get(
            reverse('wiki.feeds.recent_revisions',
                    args=(),
                    kwargs={'format': 'rss'}))
        eq_(200, resp.status_code)
        feed = pq(resp.content)
        eq_(5, len(feed.find('item')))
        for i, item in enumerate(feed.find('item')):
            desc_text = pq(item).find('description').text()
            ok_('by:</h3><p>testuser</p>' in desc_text)
            ok_('<h3>Comment:</h3><p>Revision' in desc_text)
            if "Edited" in desc_text:
                ok_('$compare?to' in desc_text)
                ok_('diff_chg' in desc_text)
            ok_('$edit' in desc_text)
            ok_('$history' in desc_text)

        resp = self.client.get(
            reverse('wiki.feeds.recent_revisions',
                    args=(),
                    kwargs={'format': 'rss'}) + '?limit=2')
        feed = pq(resp.content)
        eq_(2, len(feed.find('item')))

        resp = self.client.get(
            reverse('wiki.feeds.recent_revisions',
                    args=(),
                    kwargs={'format': 'rss'}) + '?limit=2&page=1')
        ok_('Revision 5' in resp.content)
        ok_('Revision 4' in resp.content)

        resp = self.client.get(
            reverse('wiki.feeds.recent_revisions',
                    args=(),
                    kwargs={'format': 'rss'}) + '?limit=2&page=2')
        ok_('Revision 3' in resp.content)
        ok_('Revision 2' in resp.content)
Example #38
0
    def test_visit_count_from_analytics(self, _build_request):
        """Verify stored visit counts from mocked analytics data.

        It has some nasty non-ASCII chars in it.
        """
        execute = _build_request.return_value.get.return_value.execute
        execute.return_value = PAGEVIEWS_BY_DOCUMENT_RESPONSE

        d1 = revision(document=document(slug='hellỗ', save=True),
                      is_approved=True,
                      save=True).document
        d2 = revision(document=document(slug='there', save=True),
                      is_approved=True,
                      save=True).document

        WikiDocumentVisits.reload_period_from_analytics(LAST_7_DAYS)

        eq_(2, WikiDocumentVisits.objects.count())
        wdv1 = WikiDocumentVisits.objects.get(document=d1)
        eq_(27, wdv1.visits)
        eq_(LAST_7_DAYS, wdv1.period)
        wdv2 = WikiDocumentVisits.objects.get(document=d2)
        eq_(LAST_7_DAYS, wdv2.period)
Example #39
0
    def test_preview_async(self):
        """Preview a reply."""
        u = user(save=True)
        self.client.login(username=u.username, password='******')

        d = document(save=True)
        content = 'Full of awesome.'
        response = post(self.client,
                        'wiki.discuss.post_preview_async',
                        {'content': content},
                        args=[d.slug])
        eq_(200, response.status_code)
        doc = pq(response.content)
        eq_(content, doc('div.content').text())
Example #40
0
    def test_search(self, _out):
        """Test that es_search command doesn't fail"""
        call_command('essearch', 'cupcakes')

        doc = document(title=u'cupcakes rock',
                       locale=u'en-US',
                       category=10,
                       save=True)
        doc.products.add(product(title=u'firefox', slug=u'desktop', save=True))
        revision(document=doc, is_approved=True, save=True)

        self.refresh()

        call_command('essearch', 'cupcakes')
Example #41
0
    def test_edit_post(self):
        """Changing post content works."""
        u = user(save=True)
        self.client.login(username=u.username, password='******')

        d = document(save=True)
        t = thread(document=d, save=True)
        p = t.new_post(creator=u, content='foo')
        post(self.client, 'wiki.discuss.edit_post',
             {'content': 'Some new content'},
             args=[d.slug, t.id, p.id])
        edited_p = t.post_set.get(pk=p.id)

        eq_('Some new content', edited_p.content)
Example #42
0
 def test_preview(self):
     """Preview the thread post."""
     u = user(save=True)
     self.client.login(username=u.username, password='******')
     d = document(save=True)
     num_threads = d.thread_set.count()
     content = 'Full of awesome.'
     response = post(self.client, 'wiki.discuss.new_thread',
                     {'title': 'Topic', 'content': content,
                      'preview': 'any string'}, args=[d.slug])
     eq_(200, response.status_code)
     doc = pq(response.content)
     eq_(content, doc('#post-preview div.content').text())
     eq_(num_threads, d.thread_set.count())
Example #43
0
    def test_disallowed_404(self):
        """If document.allow_discussion is false, should return 404."""
        u = user(username='******', save=True)
        self.client.login(username=u.username, password='******')
        doc = document(allow_discussion=False, save=True)

        def check(url):
            response = get(self.client, url, args=[doc.slug])
            st = response.status_code
            eq_(404, st, '%s was %s, not 404' % (url, st))

        check('wiki.discuss.threads')
        check('wiki.discuss.new_thread')
        check('wiki.discuss.threads.feed')
Example #44
0
    def test_edit_thread(self):
        """Changing thread title works."""
        u = user(save=True)
        self.client.login(username=u.username, password='******')

        d = document(save=True)
        t = thread(title='Sticky Thread', document=d, creator=u, save=True)
        post(self.client,
             'wiki.discuss.edit_thread', {'title': 'A new title'},
             args=[d.slug, t.id])
        edited_t = d.thread_set.get(pk=t.id)

        eq_('Sticky Thread', t.title)
        eq_('A new title', edited_t.title)
Example #45
0
    def test_good_visit_count(self):
        """Extract visit counts from good data.

        It has some nasty non-ASCII chars in it.

        """
        d = revision(document=document(slug='hellỗ', save=True),
                     is_approved=True, save=True).document
        d2 = revision(document=document(slug='there', save=True),
                      is_approved=True, save=True).document
        # We get a str, not a unicode obj, out of the urllib call.
        eq_({d.pk: 1037639, d2.pk: 213817}, WikiDocumentVisits._visit_counts(
            '{"data": {"12/01/2010-12/07/2010": {"SubRows":{'
            '"http://support.mozilla.com/%s/kb/hellỗ":{"Attributes":{"Title":'
            '"Firefox Support Home Page | Firefox Support","UrlLink":'
            '"http://support.mozilla.com/en-US/home/"},"measures":'
            '{"Visits":1037639.0,"Views":3357731.0,"Average Time Viewed":23.0'
            '},"SubRows":null},"http://support.mozilla.com/%s/kb/there":'
            '{"Attributes":{"Title":"Startseite der Firefox-Hilfe | Firefox'
            'Support","UrlLink":"http://support.mozilla.com/de/home/"},'
            '"measures":{"Visits":213817.0,"Views":595329.0,"Average Time '
            'Viewed":25.0},"SubRows":null}}}}}'
            % ((settings.LANGUAGE_CODE,) * 2)))
Example #46
0
    def test_other_translations(self):
        """
        parent doc should list all docs for which it is parent

        A child doc should list all its parent's docs, excluding itself, and
        including its parent
        """
        parent = document(locale='en-US', title='test', save=True)
        enfant = document(locale='fr',
                          title='le test',
                          parent=parent,
                          save=True)
        bambino = document(locale='es',
                           title='el test',
                           parent=parent,
                           save=True)

        children = Document.objects.filter(parent=parent)
        eq_(list(children), parent.other_translations)

        ok_(parent in enfant.other_translations)
        ok_(bambino in enfant.other_translations)
        eq_(False, enfant in enfant.other_translations)
Example #47
0
    def test_empty_reply_errors(self):
        """Posting an empty reply shows errors."""
        u = user(save=True)
        self.client.login(username=u.username, password='******')

        d = document(save=True)
        t = thread(document=d, save=True)
        response = post(self.client,
                        'wiki.discuss.reply', {'content': ''},
                        args=[d.slug, t.id])

        doc = pq(response.content)
        error_msg = doc('ul.errorlist li a')[0]
        eq_(error_msg.text, 'Please provide a message.')
Example #48
0
    def test_update_l10n_metric_cron(self, visits_by_locale, _get_top_docs):
        """Verify the cron job creates the correct metric."""
        l10n_kind = metric_kind(code=L10N_METRIC_CODE, save=True)

        # Create the en-US document with an approved revision.
        doc = document(save=True)
        rev = revision(
            document=doc,
            is_approved=True,
            is_ready_for_localization=True,
            save=True)

        # Create an es translation that is up to date.
        es_doc = document(parent=doc, locale='es', save=True)
        revision(
            document=es_doc,
            is_approved=True,
            based_on=rev,
            save=True)

        # Create a de translation without revisions.
        document(parent=doc, locale='de', save=True)

        # Mock some calls.
        visits_by_locale.return_value = {
            'en-US': 100,
            'de': 20,
            'es': 10,
            'fr': 10,
        }
        _get_top_docs.return_value = [doc]

        # Run it and verify results. Values sould be 25% (1/1 * 10/40).
        update_l10n_metric()
        metrics = Metric.objects.filter(kind=l10n_kind)
        eq_(1, len(metrics))
        eq_(25, metrics[0].value)
Example #49
0
    def test_watch_locale(self):
        """Watch and unwatch a locale."""
        u = user(save=True)
        self.client.login(username=u.username, password='******')

        d = document(save=True)
        next_url = reverse('wiki.discuss.threads', args=[d.slug])
        response = post(self.client, 'wiki.discuss.watch_locale',
                        {'watch': 'yes', 'next': next_url})
        self.assertContains(response, 'Turn off emails')

        response = post(self.client, 'wiki.discuss.watch_locale',
                        {'watch': 'no', 'next': next_url})
        self.assertContains(response,
                            'Get emailed when there is new discussion')
Example #50
0
    def test_reindex(self, _out):
        doc = document(title=u'cupcakes rock',
                       locale=u'en-US',
                       category=10,
                       save=True)
        doc.products.add(product(title=u'firefox', slug=u'desktop', save=True))
        revision(document=doc, is_approved=True, save=True)

        self.refresh()

        call_command('esreindex')
        call_command('esreindex', '--percent=50')
        call_command('esreindex', '--criticalmass')
        call_command('esreindex', '--mapping_types=wiki_documents')
        call_command('esreindex', '--delete')
Example #51
0
    def test_unready_for_l10n(self):
        """Test status for article that is not ready for l10n"""
        locale = settings.WIKI_DEFAULT_LANGUAGE
        d = document(title='Template:test', save=True)
        revision(document=d, is_ready_for_localization=True, save=True)
        revision(document=d,
                 is_ready_for_localization=False,
                 is_approved=True,
                 significance=MAJOR_SIGNIFICANCE,
                 save=True)

        row = self.row(locale=locale)

        eq_(row['title'], d.title)
        eq_(unicode(row['status']), u'Changes Not Ready For Localization')
Example #52
0
    def test_watch_forum(self):
        """Watch and unwatch a forum."""
        u = user(save=True)
        self.client.login(username=u.username, password='******')

        d = document(save=True)
        response = post(self.client,
                        'wiki.discuss.watch_forum', {'watch': 'yes'},
                        args=[d.slug])
        self.assertContains(response, 'Stop')

        response = post(self.client,
                        'wiki.discuss.watch_forum', {'watch': 'no'},
                        args=[d.slug])
        self.assertNotContains(response, 'Stop')
Example #53
0
    def test_by_product(self):
        """Test the product filtering of the readout."""
        p = product(title='Firefox', slug='firefox', save=True)
        d = document(title='Foo', save=True)
        untranslated = revision(is_approved=True,
                                is_ready_for_localization=True,
                                document=d,
                                save=True)

        # There shouldn't be any rows yet.
        eq_(0, len(self.rows(product=p)))

        # Add the product to the document, and verify it shows up.
        d.products.add(p)
        eq_(self.row(product=p)['title'], d.title)
Example #54
0
    def test_wiki_keywords(self):
        """Make sure updating keywords updates the index."""
        # Create a document with a revision with no keywords. It
        # shouldn't show up with a document_keywords term query for
        # 'wool' since it has no keywords.
        doc = document(title=u'wool hats')
        doc.save()
        revision(document=doc, is_approved=True, save=True)
        self.refresh()
        eq_(Document.search().query(document_keywords='wool').count(), 0)

        revision(document=doc, is_approved=True, keywords='wool', save=True)
        self.refresh()

        eq_(Document.search().query(document_keywords='wool').count(), 1)
Example #55
0
    def test_edit_thread_errors(self):
        """Editing thread with too short of a title shows errors."""
        u = user(save=True)
        self.client.login(username=u.username, password='******')

        d = document(save=True)
        t = thread(document=d, creator=u, save=True)
        response = post(self.client, 'wiki.discuss.edit_thread',
                        {'title': 'wha?'}, args=[d.slug, t.id])

        doc = pq(response.content)
        errors = doc('ul.errorlist li a')
        eq_(errors[0].text,
            'Your title is too short (4 characters). ' +
            'It must be at least 5 characters.')
Example #56
0
    def test_kb_vote(self):
        """Test vote API call."""
        r1 = revision(document=document(locale='en-US', save=True), save=True)
        r2 = revision(document=document(locale='es', save=True), save=True)
        r3 = revision(document=document(locale='es', save=True), save=True)
        for r in [r1, r2, r3]:
            helpful_vote(revision=r, save=True)
            helpful_vote(revision=r, save=True)
            helpful_vote(revision=r, helpful=True, save=True)

        # All votes should be counted if we don't specify a locale
        r = self._get_api_result('kpi_kb_vote')
        eq_(r['objects'][0]['kb_helpful'], 3)
        eq_(r['objects'][0]['kb_votes'], 9)

        # Only en-US votes:
        r = self._get_api_result('kpi_kb_vote', locale='en-US')
        eq_(r['objects'][0]['kb_helpful'], 1)
        eq_(r['objects'][0]['kb_votes'], 3)

        # Only es votes:
        r = self._get_api_result('kpi_kb_vote', locale='es')
        eq_(r['objects'][0]['kb_helpful'], 2)
        eq_(r['objects'][0]['kb_votes'], 6)
Example #57
0
    def test_preview_reply(self):
        """Preview a reply."""
        u = user(save=True)
        self.client.login(username=u.username, password='******')

        d = document(save=True)
        t = thread(document=d, save=True)
        num_posts = t.post_set.count()
        content = 'Full of awesome.'
        response = post(self.client, 'wiki.discuss.reply',
                        {'content': content, 'preview': 'any string'},
                        args=[d.slug, t.id])
        eq_(200, response.status_code)
        doc = pq(response.content)
        eq_(content, doc('#post-preview div.content').text())
        eq_(num_posts, t.post_set.count())
Example #58
0
    def test_document_is_template(self):
        """is_template stays in sync with the title"""
        d = document(title='test')
        d.save()

        assert not d.is_template

        d.slug = 'Template:test'
        d.save()

        assert d.is_template

        d.slug = 'Back-to-document'
        d.save()

        assert not d.is_template
Example #59
0
    def test_counting_unready_docs(self):
        """Docs without a ready-for-l10n rev shouldn't count in total."""
        # Make a doc with an approved but not-ready-for-l10n rev:
        r = revision(document=document(title='smoo',
                                       is_localizable=True,
                                       save=True),
                     is_ready_for_localization=False,
                     is_approved=True,
                     save=True)

        # It shouldn't show up in the total:
        eq_(0, overview_rows('de')['all']['denominator'])

        r.is_ready_for_localization = True
        r.save()
        eq_(1, overview_rows('de')['all']['denominator'])
Example #60
0
    def test_correct_based_on_to_current_revision(self):
        """Assure Revision.clean() defaults based_on value to the English
        doc's current_revision when there is one."""
        # Make English rev:
        en_rev = revision(is_approved=True)
        en_rev.save()

        # Make Deutsch translation:
        de_doc = document(parent=en_rev.document, locale='de')
        de_doc.save()
        de_rev = revision(document=de_doc)

        # Set based_on to a de rev to simulate fixing broken translation source
        de_rev.based_on = de_rev
        de_rev.clean()
        eq_(en_rev.document.current_revision, de_rev.based_on)