Remove pytest and nose throughout the project.

This commit is contained in:
Tasos Katsoulas 2022-01-21 20:53:54 +02:00
Родитель 012235fd93
Коммит 84f5f7ed0a
134 изменённых файлов: 2977 добавлений и 3264 удалений

Просмотреть файл

@ -1,9 +1,7 @@
from django.contrib.contenttypes.models import ContentType
from django.test.client import RequestFactory
import factory
from authority.models import Permission
from nose.tools import eq_
from django.contrib.contenttypes.models import ContentType
from django.test.client import RequestFactory
from kitsune.access import utils as access
from kitsune.sumo.tests import TestCase
@ -58,9 +56,9 @@ class AccessTests(TestCase):
other_t = ThreadFactory()
perm = "forums_forum.thread_edit_forum"
allowed = access.has_perm_or_owns(me, perm, my_t, my_t.forum)
eq_(allowed, True)
self.assertEqual(allowed, True)
allowed = access.has_perm_or_owns(me, perm, other_t, other_t.forum)
eq_(allowed, False)
self.assertEqual(allowed, False)
def test_has_perm_per_object(self):
"""Assert has_perm checks per-object permissions correctly."""

Просмотреть файл

@ -2,9 +2,7 @@ from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponse
from django.test.client import RequestFactory
from nose.tools import eq_
from kitsune.access.decorators import logout_required, login_required, permission_required
from kitsune.access.decorators import login_required, logout_required, permission_required
from kitsune.sumo.tests import TestCase
from kitsune.users.tests import UserFactory
@ -19,22 +17,22 @@ class LogoutRequiredTestCase(TestCase):
request.user = AnonymousUser()
view = logout_required(simple_view)
response = view(request)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_logged_in_default(self):
request = RequestFactory().get("/foo")
request.user = UserFactory()
view = logout_required(simple_view)
response = view(request)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
def test_logged_in_argument(self):
request = RequestFactory().get("/foo")
request.user = UserFactory()
view = logout_required("/bar")(simple_view)
response = view(request)
eq_(302, response.status_code)
eq_("/bar", response["location"])
self.assertEqual(302, response.status_code)
self.assertEqual("/bar", response["location"])
def test_no_redirect_ajax(self):
"""Ajax requests should not redirect."""
@ -43,7 +41,7 @@ class LogoutRequiredTestCase(TestCase):
request.user = UserFactory()
view = logout_required(simple_view)
response = view(request)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
class LoginRequiredTestCase(TestCase):
@ -52,7 +50,7 @@ class LoginRequiredTestCase(TestCase):
request.user = AnonymousUser()
view = login_required(simple_view)
response = view(request)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
def test_logged_in_default(self):
"""Active user login."""
@ -60,7 +58,7 @@ class LoginRequiredTestCase(TestCase):
request.user = UserFactory()
view = login_required(simple_view)
response = view(request)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_logged_in_inactive(self):
"""Inactive user login not allowed by default."""
@ -68,7 +66,7 @@ class LoginRequiredTestCase(TestCase):
request.user = UserFactory(is_active=False)
view = login_required(simple_view)
response = view(request)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
def test_logged_in_inactive_allow(self):
"""Inactive user login explicitly allowed."""
@ -76,7 +74,7 @@ class LoginRequiredTestCase(TestCase):
request.user = UserFactory(is_active=False)
view = login_required(simple_view, only_active=False)
response = view(request)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_no_redirect_ajax(self):
"""Ajax requests should not redirect."""
@ -85,7 +83,7 @@ class LoginRequiredTestCase(TestCase):
request.user = AnonymousUser()
view = login_required(simple_view)
response = view(request)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
class PermissionRequiredTestCase(TestCase):
@ -94,14 +92,14 @@ class PermissionRequiredTestCase(TestCase):
request.user = AnonymousUser()
view = permission_required("perm")(simple_view)
response = view(request)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
def test_logged_in_default(self):
request = RequestFactory().get("/foo")
request.user = UserFactory()
view = permission_required("perm")(simple_view)
response = view(request)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_logged_in_inactive(self):
"""Inactive user is denied access."""
@ -109,14 +107,14 @@ class PermissionRequiredTestCase(TestCase):
request.user = UserFactory(is_active=False)
view = permission_required("perm")(simple_view)
response = view(request)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_logged_in_admin(self):
request = RequestFactory().get("/foo")
request.user = UserFactory(is_staff=True, is_superuser=True)
view = permission_required("perm")(simple_view)
response = view(request)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_no_redirect_ajax(self):
"""Ajax requests should not redirect."""
@ -125,4 +123,4 @@ class PermissionRequiredTestCase(TestCase):
request.user = AnonymousUser()
view = permission_required("perm")(simple_view)
response = view(request)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)

Просмотреть файл

@ -1,11 +1,9 @@
from datetime import datetime, timedelta
from nose.tools import eq_
from kitsune.announcements.models import Announcement
from kitsune.announcements.tests import AnnouncementFactory
from kitsune.sumo.tests import TestCase
from kitsune.users.tests import UserFactory, GroupFactory
from kitsune.users.tests import GroupFactory, UserFactory
from kitsune.wiki.tests import LocaleFactory
@ -23,7 +21,7 @@ class AnnouncementModelTests(TestCase):
show_after=datetime.now() - timedelta(days=2),
show_until=datetime.now() + timedelta(days=2),
)
eq_(1, Announcement.get_site_wide().count())
self.assertEqual(1, Announcement.get_site_wide().count())
def test_always_visible(self):
"""Always visible announcements are shown."""
@ -34,13 +32,13 @@ class AnnouncementModelTests(TestCase):
)
site_wide = Announcement.get_site_wide()
eq_(1, site_wide.count())
eq_("stardate 43125", site_wide[0].content)
self.assertEqual(1, site_wide.count())
self.assertEqual("stardate 43125", site_wide[0].content)
def test_group_excluded(self):
"""Announcements in a group are not shown."""
AnnouncementFactory(group=self.group)
eq_(0, Announcement.get_site_wide().count())
self.assertEqual(0, Announcement.get_site_wide().count())
def test_get_for_group_id(self):
"""If no groups are passed, nothing is returned."""
@ -50,8 +48,8 @@ class AnnouncementModelTests(TestCase):
a = AnnouncementFactory(group=self.group)
group_ann = Announcement.get_for_group_id(self.group.id)
eq_(1, len(group_ann))
eq_(a, group_ann[0])
self.assertEqual(1, len(group_ann))
self.assertEqual(a, group_ann[0])
def test_get_for_locale_name(self):
"""Announcements for a specific locale are shown."""
@ -61,5 +59,5 @@ class AnnouncementModelTests(TestCase):
a = AnnouncementFactory(locale=self.locale)
locale_ann = Announcement.get_for_locale_name(self.locale.locale)
eq_(1, locale_ann.count())
eq_(a, locale_ann[0])
self.assertEqual(1, locale_ann.count())
self.assertEqual(a, locale_ann[0])

Просмотреть файл

@ -1,13 +1,12 @@
from unittest import mock
from django.contrib.sites.models import Site
from django.core import mail
from unittest import mock
from nose.tools import eq_
from kitsune.announcements.tasks import send_group_email
from kitsune.announcements.tests import AnnouncementFactory
from kitsune.sumo.tests import TestCase
from kitsune.users.tests import UserFactory, GroupFactory
from kitsune.users.tests import GroupFactory, UserFactory
class AnnouncementSaveTests(TestCase):
@ -29,14 +28,14 @@ class AnnouncementSaveTests(TestCase):
a = self._setup_announcement()
# Signal fired, emails sent.
eq_(2, len(mail.outbox))
self.assertEqual(2, len(mail.outbox))
assert a.content in mail.outbox[0].body
assert a.content in mail.outbox[1].body
# No new emails sent when modifying.
a.creator = self.user
a.save()
eq_(2, len(mail.outbox))
self.assertEqual(2, len(mail.outbox))
@mock.patch.object(Site.objects, "get_current")
def test_create_invisible_announcement(self, get_current):
@ -44,7 +43,7 @@ class AnnouncementSaveTests(TestCase):
get_current.return_value.domain = "testserver"
self._setup_announcement(visible_dates=False)
eq_(0, len(mail.outbox))
self.assertEqual(0, len(mail.outbox))
@mock.patch.object(Site.objects, "get_current")
def test_send_nonexistent(self, get_current):
@ -52,4 +51,4 @@ class AnnouncementSaveTests(TestCase):
get_current.return_value.domain = "testserver"
send_group_email(1)
eq_(0, len(mail.outbox))
self.assertEqual(0, len(mail.outbox))

Просмотреть файл

@ -1,7 +1,5 @@
from datetime import datetime
from nose.tools import eq_
from kitsune.announcements.models import Announcement
from kitsune.announcements.tests import AnnouncementFactory
from kitsune.sumo.tests import TestCase
@ -24,8 +22,8 @@ class TestCreateLocaleAnnouncement(TestCase):
"show_after": "2012-01-01",
},
)
eq_(resp.status_code, status)
eq_(Announcement.objects.count(), count)
self.assertEqual(resp.status_code, status)
self.assertEqual(Announcement.objects.count(), count)
def test_create(self):
u = UserFactory(is_superuser=1)
@ -74,8 +72,8 @@ class TestDeleteAnnouncement(TestCase):
"""Login, or other setup, then call this."""
url = reverse("announcements.delete", locale="es", args=(id,))
resp = self.client.post(url)
eq_(resp.status_code, status)
eq_(Announcement.objects.count(), count)
self.assertEqual(resp.status_code, status)
self.assertEqual(Announcement.objects.count(), count)
def test_delete(self):
u = UserFactory(is_superuser=1)

Просмотреть файл

@ -1,12 +1,11 @@
from datetime import datetime, timedelta
from unittest import mock
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core import mail
from django.core.management import call_command
from django.test.utils import override_settings
from nose.tools import eq_
from kitsune.questions.tests import AnswerFactory, QuestionFactory
from kitsune.sumo.tests import TestCase, attrs_eq
@ -39,7 +38,7 @@ class WelcomeEmailsTests(TestCase):
# u1 was the asker, and so did not make a contribution.
# u2 has already recieved the email
eq_(len(mail.outbox), 1)
self.assertEqual(len(mail.outbox), 1)
attrs_eq(mail.outbox[0], to=[u3.email])
# Links should be locale-neutral
@ -57,7 +56,7 @@ class WelcomeEmailsTests(TestCase):
# u3's flag should now be set.
u3 = User.objects.get(id=u3.id)
eq_(u3.profile.first_answer_email_sent, True)
self.assertEqual(u3.profile.first_answer_email_sent, True)
@override_settings(WIKI_DEFAULT_LANGUAGE="en-US")
@mock.patch.object(Site.objects, "get_current")
@ -81,7 +80,7 @@ class WelcomeEmailsTests(TestCase):
# There should be an email for u1 only.
# u2 has already recieved the email
eq_(len(mail.outbox), 1)
self.assertEqual(len(mail.outbox), 1)
attrs_eq(mail.outbox[0], to=[u1.email])
# Links should be locale-neutral
@ -95,4 +94,4 @@ class WelcomeEmailsTests(TestCase):
# u3's flag should now be set.
u1 = User.objects.get(id=u1.id)
eq_(u1.profile.first_l10n_email_sent, True)
self.assertEqual(u1.profile.first_l10n_email_sent, True)

Просмотреть файл

@ -1,4 +1,3 @@
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.forums.tests import ThreadFactory
@ -21,7 +20,7 @@ class UserSearchTests(Elastic7TestCase):
UserFactory(username="foo", profile__name="Foo Bar")
self.refresh()
response = self.client.get(urlparams(reverse("community.search"), q="baz"))
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
assert b"No users were found" in response.content
def test_results(self):
@ -33,16 +32,16 @@ class UserSearchTests(Elastic7TestCase):
# Searching for "bam" should return 1 user.
response = self.client.get(urlparams(reverse("community.search"), q="bam"))
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
doc = pq(response.content)
eq_(len(doc(".results-user")), 1)
self.assertEqual(len(doc(".results-user")), 1)
# Searching for "bar" should return both users.
response = self.client.get(urlparams(reverse("community.search"), q="bar"))
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
doc = pq(response.content)
eq_(len(doc(".results-user")), 2)
self.assertEqual(len(doc(".results-user")), 2)
class LandingTests(Elastic7TestCase):
@ -65,20 +64,20 @@ class LandingTests(Elastic7TestCase):
self.refresh()
response = self.client.get(urlparams(reverse("community.home")))
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
doc = pq(response.content)
eq_(1, len(doc("ul.kb > li")))
eq_(2, len(doc("ul.l10n > li")))
eq_(3, len(doc("ul.questions > li")))
self.assertEqual(1, len(doc("ul.kb > li")))
self.assertEqual(2, len(doc("ul.l10n > li")))
self.assertEqual(3, len(doc("ul.questions > li")))
def test_wiki_section(self):
"""Verify the wiki doc appears on the landing page."""
# If "Mozilla News" article doesn't exist, home page
# should still work and omit the section.
response = self.client.get(urlparams(reverse("community.home")))
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
doc = pq(response.content)
eq_(len(doc("#doc-content")), 0)
self.assertEqual(len(doc("#doc-content")), 0)
# Create the "Mozilla News" article and verify it on home page.
d = DocumentFactory(title="Community Hub News", slug="community-hub-news")
@ -86,10 +85,10 @@ class LandingTests(Elastic7TestCase):
d.current_revision = rev
d.save()
response = self.client.get(urlparams(reverse("community.home")))
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
doc = pq(response.content)
community_news = doc("#doc-content")
eq_(len(community_news), 1)
self.assertEqual(len(community_news), 1)
assert "splendid" in community_news.text()
def test_recent_threads(self):
@ -99,9 +98,9 @@ class LandingTests(Elastic7TestCase):
self.refresh()
response = self.client.get(urlparams(reverse("community.home")))
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
doc = pq(response.content)
eq_(1, len(doc("#recent-threads")))
self.assertEqual(1, len(doc("#recent-threads")))
assert "we are SUMO!" in doc("#recent-threads td").html()
@ -116,7 +115,7 @@ class TopContributorsTests(Elastic7TestCase):
response = self.client.get(
urlparams(reverse("community.top_contributors", args=["foobar"]))
)
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
def test_top_questions(self):
a1 = AnswerFactory()
@ -127,9 +126,9 @@ class TopContributorsTests(Elastic7TestCase):
response = self.client.get(
urlparams(reverse("community.top_contributors", args=["questions"]))
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(2, len(doc("li.results-user")))
self.assertEqual(2, len(doc("li.results-user")))
assert str(a1.creator.username) in response.content
assert str(a2.creator.username) in response.content
@ -141,9 +140,9 @@ class TopContributorsTests(Elastic7TestCase):
self.refresh()
response = self.client.get(urlparams(reverse("community.top_contributors", args=["kb"])))
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(2, len(doc("li.results-user")))
self.assertEqual(2, len(doc("li.results-user")))
assert str(r1.creator.username) in response.content
assert str(r2.creator.username) in response.content
@ -155,8 +154,8 @@ class TopContributorsTests(Elastic7TestCase):
self.refresh()
response = self.client.get(urlparams(reverse("community.top_contributors", args=["l10n"])))
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(2, len(doc("li.results-user")))
self.assertEqual(2, len(doc("li.results-user")))
assert str(r1.creator.username) in response.content
assert str(r2.creator.username) in response.content

Просмотреть файл

@ -1,7 +1,5 @@
from datetime import date, datetime, timedelta
from nose.tools import eq_
from kitsune.community.utils import (
top_contributors_kb,
top_contributors_l10n,
@ -27,21 +25,21 @@ class TopContributorTests(Elastic7TestCase):
# By default, we should only get 2 top contributors back.
top, _ = top_contributors_kb()
eq_(2, len(top))
self.assertEqual(2, len(top))
assert r4.creator_id not in [u["term"] for u in top]
eq_(r1.creator_id, top[0]["term"])
self.assertEqual(r1.creator_id, top[0]["term"])
# If we specify an older start, then we get all 3.
top, _ = top_contributors_kb(start=date.today() - timedelta(days=92))
eq_(3, len(top))
self.assertEqual(3, len(top))
# If we also specify an older end date, we only get the creator for
# the older revision.
top, _ = top_contributors_kb(
start=date.today() - timedelta(days=92), end=date.today() - timedelta(days=1)
)
eq_(1, len(top))
eq_(r4.creator_id, top[0]["term"])
self.assertEqual(1, len(top))
self.assertEqual(r4.creator_id, top[0]["term"])
def test_top_contributors_l10n(self):
d = DocumentFactory(locale="es")
@ -62,18 +60,18 @@ class TopContributorTests(Elastic7TestCase):
# By default, we should only get 2 top contributors back for 'es'.
top, _ = top_contributors_l10n(locale="es")
eq_(2, len(top))
self.assertEqual(2, len(top))
assert es4.creator_id not in [u["term"] for u in top]
eq_(es1.creator_id, top[0]["term"])
self.assertEqual(es1.creator_id, top[0]["term"])
# By default, we should only get 1 top contributors back for 'de'.
top, _ = top_contributors_l10n(locale="de")
eq_(1, len(top))
eq_(de1.creator_id, top[0]["term"])
self.assertEqual(1, len(top))
self.assertEqual(de1.creator_id, top[0]["term"])
# If no locale is passed, it includes all locales except en-US.
top, _ = top_contributors_l10n()
eq_(3, len(top))
self.assertEqual(3, len(top))
def test_top_contributors_questions(self):
firefox = ProductFactory(slug="firefox")
@ -89,13 +87,13 @@ class TopContributorTests(Elastic7TestCase):
# By default, we should only get 2 top contributors back.
top, _ = top_contributors_questions()
eq_(2, len(top))
self.assertEqual(2, len(top))
assert a4.creator_id not in [u["term"] for u in top]
eq_(a1.creator_id, top[0]["term"])
self.assertEqual(a1.creator_id, top[0]["term"])
# Verify, filtering of Firefox questions only.
top, _ = top_contributors_questions(product=firefox.slug)
eq_(1, len(top))
eq_(a1.creator_id, top[0]["term"])
self.assertEqual(1, len(top))
self.assertEqual(a1.creator_id, top[0]["term"])
top, _ = top_contributors_questions(product=fxos.slug)
eq_(2, len(top))
self.assertEqual(2, len(top))

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.search.tests import Elastic7TestCase
from kitsune.sumo.tests import LocalizingClient
from kitsune.sumo.urlresolvers import reverse
@ -14,4 +12,4 @@ class ContributorsMetricsTests(Elastic7TestCase):
def test_it_works(self):
url = reverse("community.metrics")
res = self.client.get(url)
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)

Просмотреть файл

@ -1,8 +1,6 @@
import json
from datetime import date, timedelta
from nose.tools import eq_
from kitsune.dashboards.models import METRIC_CODE_CHOICES
from kitsune.dashboards.tests import WikiMetricFactory
from kitsune.products.tests import ProductFactory
@ -26,17 +24,17 @@ class WikiMetricAPITests(TestCase):
# Call the API.
response = self.client.get(urlparams(reverse("api.wikimetric_list"), format="json"))
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
results = json.loads(response.content)["results"]
# Verify the results are what we created.
eq_(10, len(results))
self.assertEqual(10, len(results))
for i in range(10):
result = results[i]
eq_(i, result["value"])
eq_(METRIC_CODE_CHOICES[i % len(METRIC_CODE_CHOICES)][0], result["code"])
eq_(str(today - timedelta(days=i)), result["date"])
self.assertEqual(i, result["value"])
self.assertEqual(METRIC_CODE_CHOICES[i % len(METRIC_CODE_CHOICES)][0], result["code"])
self.assertEqual(str(today - timedelta(days=i)), result["date"])
def test_product_filter(self):
"""Test filtering results by product."""
@ -57,19 +55,19 @@ class WikiMetricAPITests(TestCase):
response = self.client.get(
urlparams(reverse("api.wikimetric_list"), format="json", product=p1.slug)
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
results = json.loads(response.content)["results"]
eq_(3, len(results))
self.assertEqual(3, len(results))
# Call and verify the API for product=p1.
response = self.client.get(
urlparams(reverse("api.wikimetric_list"), format="json", product=p2.slug)
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
results = json.loads(response.content)["results"]
eq_(4, len(results))
self.assertEqual(4, len(results))
def test_locale_filter(self):
"""Test filtering results by locale."""
@ -86,19 +84,19 @@ class WikiMetricAPITests(TestCase):
response = self.client.get(
urlparams(reverse("api.wikimetric_list"), format="json", locale="es")
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
results = json.loads(response.content)["results"]
eq_(3, len(results))
self.assertEqual(3, len(results))
# Call and verify the API for locale=fr.
response = self.client.get(
urlparams(reverse("api.wikimetric_list"), format="json", locale="fr")
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
results = json.loads(response.content)["results"]
eq_(1, len(results))
self.assertEqual(1, len(results))
def test_code_filter(self):
"""Test filtering results by code."""
@ -117,10 +115,10 @@ class WikiMetricAPITests(TestCase):
reverse("api.wikimetric_list"), format="json", code=METRIC_CODE_CHOICES[0][0]
)
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
results = json.loads(response.content)["results"]
eq_(3, len(results))
self.assertEqual(3, len(results))
# Call and verify the API for code=METRIC_CODE_CHOICES[1].
response = self.client.get(
@ -128,7 +126,7 @@ class WikiMetricAPITests(TestCase):
reverse("api.wikimetric_list"), format="json", code=METRIC_CODE_CHOICES[1][0]
)
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
results = json.loads(response.content)["results"]
eq_(1, len(results))
self.assertEqual(1, len(results))

Просмотреть файл

@ -3,7 +3,6 @@ from datetime import date, timedelta
from django.conf import settings
from django.core.management import call_command
from nose.tools import eq_
from kitsune.dashboards.management.commands.cache_most_unhelpful_kb_articles import (
_get_current_unhelpful,
@ -36,12 +35,12 @@ class TopUnhelpfulArticlesTests(TestCase):
def test_no_old_articles(self):
"""Make sure _get_old_articles() returns nothing with no votes."""
result = _get_old_unhelpful()
eq_(0, len(result))
self.assertEqual(0, len(result))
def test_no_current_articles(self):
"""Make sure _get_current_articles() returns nothing with no votes."""
result = _get_current_unhelpful({})
eq_(0, len(result))
self.assertEqual(0, len(result))
def test_old_articles(self):
"""Returns unhelpful votes within time range"""
@ -55,9 +54,9 @@ class TopUnhelpfulArticlesTests(TestCase):
_add_vote_in_past(r, 1, 10)
result = _get_old_unhelpful()
eq_(1, len(result))
self.assertEqual(1, len(result))
self.assertAlmostEqual(0.2, result[r.document.id]["percentage"])
eq_(5, result[r.document.id]["total"])
self.assertEqual(5, result[r.document.id]["total"])
def test_old_articles_helpful(self):
"""Doesn't return helpful votes within range"""
@ -69,7 +68,7 @@ class TopUnhelpfulArticlesTests(TestCase):
_add_vote_in_past(r, 0, 10)
result = _get_old_unhelpful()
eq_(0, len(result))
self.assertEqual(0, len(result))
def test_current_articles(self):
"""Returns unhelpful votes within time range"""
@ -84,12 +83,12 @@ class TopUnhelpfulArticlesTests(TestCase):
old_data = {r.document.id: {"percentage": 0.2, "total": 5.0}}
result = _get_current_unhelpful(old_data)
eq_(1, len(result))
self.assertEqual(1, len(result))
self.assertAlmostEqual(0.4, result[r.document.id]["currperc"])
self.assertAlmostEqual(
0.4 - old_data[r.document.id]["percentage"], result[r.document.id]["diffperc"]
)
eq_(5, result[r.document.id]["total"])
self.assertEqual(5, result[r.document.id]["total"])
def test_current_articles_helpful(self):
"""Doesn't return helpful votes within time range"""
@ -104,7 +103,7 @@ class TopUnhelpfulArticlesTests(TestCase):
old_data = {r.document.id: {"percentage": 0.2, "total": 5.0}}
result = _get_current_unhelpful(old_data)
eq_(0, len(result))
self.assertEqual(0, len(result))
def test_current_articles_not_in_old(self):
"""Unhelpful articles in current but not in old works"""
@ -120,10 +119,10 @@ class TopUnhelpfulArticlesTests(TestCase):
result = _get_current_unhelpful(old_data)
eq_(1, len(result))
self.assertEqual(1, len(result))
self.assertAlmostEqual(0.4, result[r.document.id]["currperc"])
self.assertAlmostEqual(0, result[r.document.id]["diffperc"])
eq_(5, result[r.document.id]["total"])
self.assertEqual(5, result[r.document.id]["total"])
class TopUnhelpfulArticlesCommandTests(TestCase):
@ -146,7 +145,7 @@ class TopUnhelpfulArticlesCommandTests(TestCase):
def test_no_articles(self):
"""No articles returns no unhelpful articles."""
call_command("cache_most_unhelpful_kb_articles")
eq_(0, self.redis.llen(self.REDIS_KEY))
self.assertEqual(0, self.redis.llen(self.REDIS_KEY))
def test_caching_unhelpful(self):
"""Command should get the unhelpful articles."""
@ -160,9 +159,9 @@ class TopUnhelpfulArticlesCommandTests(TestCase):
call_command("cache_most_unhelpful_kb_articles")
eq_(1, self.redis.llen(self.REDIS_KEY))
self.assertEqual(1, self.redis.llen(self.REDIS_KEY))
result = self.redis.lrange(self.REDIS_KEY, 0, 1)
eq_(
self.assertEqual(
"%d::%.1f::%.1f::%.1f::%.1f::%s::%s"
% (r.document.id, 5.0, 0.4, 0.0, 0.0, r.document.slug, r.document.title),
result[0],
@ -180,7 +179,7 @@ class TopUnhelpfulArticlesCommandTests(TestCase):
call_command("cache_most_unhelpful_kb_articles")
eq_(0, self.redis.llen(self.REDIS_KEY))
self.assertEqual(0, self.redis.llen(self.REDIS_KEY))
def test_caching_changed_helpfulness(self):
"""Changed helpfulness should be calculated correctly."""
@ -200,9 +199,9 @@ class TopUnhelpfulArticlesCommandTests(TestCase):
call_command("cache_most_unhelpful_kb_articles")
eq_(1, self.redis.llen(self.REDIS_KEY))
self.assertEqual(1, self.redis.llen(self.REDIS_KEY))
result = self.redis.lrange(self.REDIS_KEY, 0, 1)
eq_(
self.assertEqual(
"%d::%.1f::%.1f::%.1f::%.1f::%s::%s"
% (r.document.id, 5.0, 0.4, 0.2, 0.0, r.document.slug, r.document.title),
result[0],
@ -239,7 +238,7 @@ class TopUnhelpfulArticlesCommandTests(TestCase):
call_command("cache_most_unhelpful_kb_articles")
eq_(3, self.redis.llen(self.REDIS_KEY))
self.assertEqual(3, self.redis.llen(self.REDIS_KEY))
result = self.redis.lrange(self.REDIS_KEY, 0, 3)
assert "%d::%.1f:" % (r2.document.id, 242.0) in result[0]
assert "%d::%.1f:" % (r3.document.id, 122.0) in result[1]
@ -282,40 +281,88 @@ class L10nMetricsTests(TestCase):
call_command("update_l10n_coverage_metrics")
# Verify es metrics.
eq_(6, WikiMetric.objects.filter(locale="es").count())
eq_(5.0, WikiMetric.objects.get(locale="es", product=p, code=L10N_TOP20_CODE).value)
eq_(5.0, WikiMetric.objects.get(locale="es", product=p, code=L10N_TOP100_CODE).value)
eq_(5.0, WikiMetric.objects.get(locale="es", product=p, code=L10N_ALL_CODE).value)
eq_(5.0, WikiMetric.objects.get(locale="es", product=None, code=L10N_TOP20_CODE).value)
eq_(5.0, WikiMetric.objects.get(locale="es", product=None, code=L10N_TOP100_CODE).value)
eq_(5.0, WikiMetric.objects.get(locale="es", product=None, code=L10N_ALL_CODE).value)
self.assertEqual(6, WikiMetric.objects.filter(locale="es").count())
self.assertEqual(
5.0, WikiMetric.objects.get(locale="es", product=p, code=L10N_TOP20_CODE).value
)
self.assertEqual(
5.0, WikiMetric.objects.get(locale="es", product=p, code=L10N_TOP100_CODE).value
)
self.assertEqual(
5.0, WikiMetric.objects.get(locale="es", product=p, code=L10N_ALL_CODE).value
)
self.assertEqual(
5.0, WikiMetric.objects.get(locale="es", product=None, code=L10N_TOP20_CODE).value
)
self.assertEqual(
5.0, WikiMetric.objects.get(locale="es", product=None, code=L10N_TOP100_CODE).value
)
self.assertEqual(
5.0, WikiMetric.objects.get(locale="es", product=None, code=L10N_ALL_CODE).value
)
# Verify de metrics.
eq_(6, WikiMetric.objects.filter(locale="de").count())
eq_(10.0, WikiMetric.objects.get(locale="de", product=p, code=L10N_TOP20_CODE).value)
eq_(10.0, WikiMetric.objects.get(locale="de", product=None, code=L10N_TOP100_CODE).value)
eq_(10.0, WikiMetric.objects.get(locale="de", product=p, code=L10N_ALL_CODE).value)
eq_(10.0, WikiMetric.objects.get(locale="de", product=None, code=L10N_TOP20_CODE).value)
eq_(10.0, WikiMetric.objects.get(locale="de", product=None, code=L10N_TOP100_CODE).value)
eq_(10.0, WikiMetric.objects.get(locale="de", product=None, code=L10N_ALL_CODE).value)
self.assertEqual(6, WikiMetric.objects.filter(locale="de").count())
self.assertEqual(
10.0, WikiMetric.objects.get(locale="de", product=p, code=L10N_TOP20_CODE).value
)
self.assertEqual(
10.0, WikiMetric.objects.get(locale="de", product=None, code=L10N_TOP100_CODE).value
)
self.assertEqual(
10.0, WikiMetric.objects.get(locale="de", product=p, code=L10N_ALL_CODE).value
)
self.assertEqual(
10.0, WikiMetric.objects.get(locale="de", product=None, code=L10N_TOP20_CODE).value
)
self.assertEqual(
10.0, WikiMetric.objects.get(locale="de", product=None, code=L10N_TOP100_CODE).value
)
self.assertEqual(
10.0, WikiMetric.objects.get(locale="de", product=None, code=L10N_ALL_CODE).value
)
# Verify ru metrics.
eq_(6, WikiMetric.objects.filter(locale="ru").count())
eq_(100.0, WikiMetric.objects.get(locale="ru", product=p, code=L10N_TOP20_CODE).value)
eq_(100.0, WikiMetric.objects.get(locale="ru", product=None, code=L10N_TOP100_CODE).value)
eq_(100.0, WikiMetric.objects.get(locale="ru", product=p, code=L10N_ALL_CODE).value)
eq_(100.0, WikiMetric.objects.get(locale="ru", product=None, code=L10N_TOP20_CODE).value)
eq_(100.0, WikiMetric.objects.get(locale="ru", product=None, code=L10N_TOP100_CODE).value)
eq_(100.0, WikiMetric.objects.get(locale="ru", product=None, code=L10N_ALL_CODE).value)
self.assertEqual(6, WikiMetric.objects.filter(locale="ru").count())
self.assertEqual(
100.0, WikiMetric.objects.get(locale="ru", product=p, code=L10N_TOP20_CODE).value
)
self.assertEqual(
100.0, WikiMetric.objects.get(locale="ru", product=None, code=L10N_TOP100_CODE).value
)
self.assertEqual(
100.0, WikiMetric.objects.get(locale="ru", product=p, code=L10N_ALL_CODE).value
)
self.assertEqual(
100.0, WikiMetric.objects.get(locale="ru", product=None, code=L10N_TOP20_CODE).value
)
self.assertEqual(
100.0, WikiMetric.objects.get(locale="ru", product=None, code=L10N_TOP100_CODE).value
)
self.assertEqual(
100.0, WikiMetric.objects.get(locale="ru", product=None, code=L10N_ALL_CODE).value
)
# Verify it metrics.
eq_(6, WikiMetric.objects.filter(locale="it").count())
eq_(0.0, WikiMetric.objects.get(locale="it", product=p, code=L10N_TOP20_CODE).value)
eq_(0.0, WikiMetric.objects.get(locale="it", product=None, code=L10N_TOP100_CODE).value)
eq_(0.0, WikiMetric.objects.get(locale="it", product=p, code=L10N_ALL_CODE).value)
eq_(0.0, WikiMetric.objects.get(locale="it", product=None, code=L10N_TOP20_CODE).value)
eq_(0.0, WikiMetric.objects.get(locale="it", product=None, code=L10N_TOP100_CODE).value)
eq_(0.0, WikiMetric.objects.get(locale="it", product=None, code=L10N_ALL_CODE).value)
self.assertEqual(6, WikiMetric.objects.filter(locale="it").count())
self.assertEqual(
0.0, WikiMetric.objects.get(locale="it", product=p, code=L10N_TOP20_CODE).value
)
self.assertEqual(
0.0, WikiMetric.objects.get(locale="it", product=None, code=L10N_TOP100_CODE).value
)
self.assertEqual(
0.0, WikiMetric.objects.get(locale="it", product=p, code=L10N_ALL_CODE).value
)
self.assertEqual(
0.0, WikiMetric.objects.get(locale="it", product=None, code=L10N_TOP20_CODE).value
)
self.assertEqual(
0.0, WikiMetric.objects.get(locale="it", product=None, code=L10N_TOP100_CODE).value
)
self.assertEqual(
0.0, WikiMetric.objects.get(locale="it", product=None, code=L10N_ALL_CODE).value
)
def test_update_active_contributor_metrics(self):
"""Test the command that updates active contributor metrics."""
@ -352,7 +399,15 @@ class L10nMetricsTests(TestCase):
# Call the command.
call_command("update_l10n_contributor_metrics", str(day))
eq_(3.0, WikiMetric.objects.get(locale="en-US", product=None, date=start_date).value)
eq_(1.0, WikiMetric.objects.get(locale="en-US", product=p, date=start_date).value)
eq_(4.0, WikiMetric.objects.get(locale="es", product=None, date=start_date).value)
eq_(0.0, WikiMetric.objects.get(locale="es", product=p, date=start_date).value)
self.assertEqual(
3.0, WikiMetric.objects.get(locale="en-US", product=None, date=start_date).value
)
self.assertEqual(
1.0, WikiMetric.objects.get(locale="en-US", product=p, date=start_date).value
)
self.assertEqual(
4.0, WikiMetric.objects.get(locale="es", product=None, date=start_date).value
)
self.assertEqual(
0.0, WikiMetric.objects.get(locale="es", product=p, date=start_date).value
)

Просмотреть файл

@ -1,9 +1,8 @@
# -*- coding: utf-8 -*-
from unittest.mock import patch
from nose.tools import eq_
from kitsune.dashboards import models
from kitsune.dashboards.models import WikiDocumentVisits, LAST_7_DAYS, googleanalytics
from kitsune.dashboards.models import LAST_7_DAYS, WikiDocumentVisits, googleanalytics
from kitsune.sumo.tests import TestCase
from kitsune.wiki.tests import ApprovedRevisionFactory
@ -28,12 +27,12 @@ class DocumentVisitsTests(TestCase):
WikiDocumentVisits.reload_period_from_analytics(LAST_7_DAYS)
eq_(2, WikiDocumentVisits.objects.count())
self.assertEqual(2, WikiDocumentVisits.objects.count())
wdv1 = WikiDocumentVisits.objects.get(document=d1)
eq_(27, wdv1.visits)
eq_(LAST_7_DAYS, wdv1.period)
self.assertEqual(27, wdv1.visits)
self.assertEqual(LAST_7_DAYS, wdv1.period)
wdv2 = WikiDocumentVisits.objects.get(document=d2)
eq_(LAST_7_DAYS, wdv2.period)
self.assertEqual(LAST_7_DAYS, wdv2.period)
PAGEVIEWS_BY_DOCUMENT_RESPONSE = {

Просмотреть файл

@ -1,43 +1,41 @@
from datetime import datetime
from kitsune.sumo.models import ModelBase
from django.conf import settings
from nose.tools import eq_
from kitsune.dashboards.readouts import (
UnreviewedReadout,
kb_overview_rows,
TemplateTranslationsReadout,
l10n_overview_rows,
MostVisitedDefaultLanguageReadout,
MostVisitedTranslationsReadout,
UnreadyForLocalizationReadout,
NeedsChangesReadout,
TemplateReadout,
HowToContributeReadout,
AdministrationReadout,
CannedResponsesReadout,
HowToContributeReadout,
MostVisitedDefaultLanguageReadout,
MostVisitedTranslationsReadout,
NeedsChangesReadout,
TemplateReadout,
TemplateTranslationsReadout,
UnreadyForLocalizationReadout,
UnreviewedReadout,
kb_overview_rows,
l10n_overview_rows,
)
from kitsune.products.tests import ProductFactory
from kitsune.sumo.models import ModelBase
from kitsune.sumo.tests import TestCase
from kitsune.wiki.config import (
MAJOR_SIGNIFICANCE,
MEDIUM_SIGNIFICANCE,
TYPO_SIGNIFICANCE,
HOW_TO_CONTRIBUTE_CATEGORY,
ADMINISTRATION_CATEGORY,
CANNED_RESPONSES_CATEGORY,
CATEGORIES,
HOW_TO_CONTRIBUTE_CATEGORY,
MAJOR_SIGNIFICANCE,
MEDIUM_SIGNIFICANCE,
TEMPLATES_CATEGORY,
TYPO_SIGNIFICANCE,
)
from kitsune.wiki.config import CATEGORIES
from kitsune.wiki.tests import (
TranslatedRevisionFactory,
ApprovedRevisionFactory,
DocumentFactory,
RedirectRevisionFactory,
RevisionFactory,
TemplateDocumentFactory,
ApprovedRevisionFactory,
RedirectRevisionFactory,
TranslatedRevisionFactory,
)
@ -66,9 +64,9 @@ class ReadoutTestCase(TestCase):
class KBOverviewTests(TestCase):
def test_unapproved_articles(self):
eq_(0, len(kb_overview_rows()))
self.assertEqual(0, len(kb_overview_rows()))
RevisionFactory()
eq_(1, len(kb_overview_rows()))
self.assertEqual(1, len(kb_overview_rows()))
def test_ready_for_l10n(self):
d = DocumentFactory()
@ -77,20 +75,20 @@ class KBOverviewTests(TestCase):
d.save()
data = kb_overview_rows()
eq_(1, len(data))
eq_(False, data[0]["ready_for_l10n"])
self.assertEqual(1, len(data))
self.assertEqual(False, data[0]["ready_for_l10n"])
ApprovedRevisionFactory(document=d, is_ready_for_localization=True)
data = kb_overview_rows()
eq_(True, data[0]["ready_for_l10n"])
self.assertEqual(True, data[0]["ready_for_l10n"])
def test_filter_by_category(self):
RevisionFactory(document__category=CATEGORIES[1][0])
eq_(1, len(kb_overview_rows()))
eq_(0, len(kb_overview_rows(category=CATEGORIES[0][0])))
eq_(1, len(kb_overview_rows(category=CATEGORIES[1][0])))
self.assertEqual(1, len(kb_overview_rows()))
self.assertEqual(0, len(kb_overview_rows(category=CATEGORIES[0][0])))
self.assertEqual(1, len(kb_overview_rows(category=CATEGORIES[1][0])))
class L10NOverviewTests(TestCase):
@ -103,11 +101,11 @@ class L10NOverviewTests(TestCase):
r = ApprovedRevisionFactory(document=d, is_ready_for_localization=False)
# It shouldn't show up in the total:
eq_(0, l10n_overview_rows("de")["templates"]["denominator"])
self.assertEqual(0, l10n_overview_rows("de")["templates"]["denominator"])
r.is_ready_for_localization = True
r.save()
eq_(1, l10n_overview_rows("de")["templates"]["denominator"])
self.assertEqual(1, l10n_overview_rows("de")["templates"]["denominator"])
def test_counting_unready_docs(self):
"""Docs without a ready-for-l10n rev shouldn't count in total."""
@ -116,11 +114,11 @@ class L10NOverviewTests(TestCase):
r = ApprovedRevisionFactory(document=d, is_ready_for_localization=False)
# It shouldn't show up in the total:
eq_(0, l10n_overview_rows("de")["all"]["denominator"])
self.assertEqual(0, l10n_overview_rows("de")["all"]["denominator"])
r.is_ready_for_localization = True
r.save()
eq_(1, l10n_overview_rows("de")["all"]["denominator"])
self.assertEqual(1, l10n_overview_rows("de")["all"]["denominator"])
def test_counting_unready_parents(self):
"""Translations with no ready revs don't count in numerator
@ -136,14 +134,14 @@ class L10NOverviewTests(TestCase):
parent=parent_rev.document, locale="de", is_localizable=False
)
RevisionFactory(document=translation, is_approved=True, based_on=parent_rev)
eq_(0, l10n_overview_rows("de")["all"]["numerator"])
self.assertEqual(0, l10n_overview_rows("de")["all"]["numerator"])
def test_templates_and_docs_disjunct(self):
"""Make sure templates aren't included in the All Articles count."""
t = TranslatedRevisionFactory(document__locale="de", is_approved=True)
# It shows up in All when it's a normal doc:
eq_(1, l10n_overview_rows("de")["all"]["numerator"])
eq_(1, l10n_overview_rows("de")["all"]["denominator"])
self.assertEqual(1, l10n_overview_rows("de")["all"]["numerator"])
self.assertEqual(1, l10n_overview_rows("de")["all"]["denominator"])
t.document.parent.title = t.document.title = "Template:thing"
t.document.parent.category = TEMPLATES_CATEGORY
@ -152,8 +150,8 @@ class L10NOverviewTests(TestCase):
t.document.parent.save()
t.document.save()
# ...but not when it's a template:
eq_(0, l10n_overview_rows("de")["all"]["numerator"])
eq_(0, l10n_overview_rows("de")["all"]["denominator"])
self.assertEqual(0, l10n_overview_rows("de")["all"]["numerator"])
self.assertEqual(0, l10n_overview_rows("de")["all"]["denominator"])
def test_not_counting_outdated(self):
"""Out-of-date translations shouldn't count as "done".
@ -164,10 +162,10 @@ class L10NOverviewTests(TestCase):
"""
t = TranslatedRevisionFactory(document__locale="de", is_approved=True)
overview = l10n_overview_rows("de")
eq_(1, overview["top-20"]["numerator"])
eq_(1, overview["top-50"]["numerator"])
eq_(1, overview["top-100"]["numerator"])
eq_(1, overview["all"]["numerator"])
self.assertEqual(1, overview["top-20"]["numerator"])
self.assertEqual(1, overview["top-50"]["numerator"])
self.assertEqual(1, overview["top-100"]["numerator"])
self.assertEqual(1, overview["all"]["numerator"])
# Update the parent with a typo-level revision:
ApprovedRevisionFactory(
@ -177,10 +175,10 @@ class L10NOverviewTests(TestCase):
)
# Assert it still shows up in the numerators:
overview = l10n_overview_rows("de")
eq_(1, overview["top-20"]["numerator"])
eq_(1, overview["top-50"]["numerator"])
eq_(1, overview["top-100"]["numerator"])
eq_(1, overview["all"]["numerator"])
self.assertEqual(1, overview["top-20"]["numerator"])
self.assertEqual(1, overview["top-50"]["numerator"])
self.assertEqual(1, overview["top-100"]["numerator"])
self.assertEqual(1, overview["all"]["numerator"])
# Update the parent with a medium-level revision:
ApprovedRevisionFactory(
@ -190,19 +188,19 @@ class L10NOverviewTests(TestCase):
)
# Assert it no longer shows up in the numerators:
overview = l10n_overview_rows("de")
eq_(0, overview["all"]["numerator"])
eq_(0, overview["top-20"]["numerator"])
eq_(0, overview["top-50"]["numerator"])
eq_(0, overview["top-100"]["numerator"])
self.assertEqual(0, overview["all"]["numerator"])
self.assertEqual(0, overview["top-20"]["numerator"])
self.assertEqual(0, overview["top-50"]["numerator"])
self.assertEqual(0, overview["top-100"]["numerator"])
def test_not_counting_how_to_contribute(self):
"""Articles with the How to contribute category should not be counted."""
t = TranslatedRevisionFactory(document__locale="de", is_approved=True)
overview = l10n_overview_rows("de")
eq_(1, overview["all"]["numerator"])
eq_(1, overview["top-20"]["numerator"])
eq_(1, overview["top-50"]["numerator"])
eq_(1, overview["top-100"]["numerator"])
self.assertEqual(1, overview["all"]["numerator"])
self.assertEqual(1, overview["top-20"]["numerator"])
self.assertEqual(1, overview["top-50"]["numerator"])
self.assertEqual(1, overview["top-100"]["numerator"])
# Update the parent with the How To Contribute category
d = t.document.parent
@ -210,28 +208,28 @@ class L10NOverviewTests(TestCase):
d.save()
overview = l10n_overview_rows("de")
eq_(0, overview["all"]["numerator"])
eq_(0, overview["top-20"]["numerator"])
eq_(0, overview["top-50"]["numerator"])
eq_(0, overview["top-100"]["numerator"])
self.assertEqual(0, overview["all"]["numerator"])
self.assertEqual(0, overview["top-20"]["numerator"])
self.assertEqual(0, overview["top-50"]["numerator"])
self.assertEqual(0, overview["top-100"]["numerator"])
def test_not_counting_untranslated(self):
"""Translations with no approved revisions shouldn't count as done."""
TranslatedRevisionFactory(document__locale="de", is_approved=False)
overview = l10n_overview_rows("de")
eq_(0, overview["top-20"]["numerator"])
eq_(0, overview["top-50"]["numerator"])
eq_(0, overview["top-100"]["numerator"])
eq_(0, overview["all"]["numerator"])
self.assertEqual(0, overview["top-20"]["numerator"])
self.assertEqual(0, overview["top-50"]["numerator"])
self.assertEqual(0, overview["top-100"]["numerator"])
self.assertEqual(0, overview["all"]["numerator"])
def test_not_counting_templates(self):
"""Articles in the Templates category should not be counted."""
t = TranslatedRevisionFactory(document__locale="de", is_approved=True)
overview = l10n_overview_rows("de")
eq_(1, overview["all"]["numerator"])
eq_(1, overview["top-20"]["numerator"])
eq_(1, overview["top-50"]["numerator"])
eq_(1, overview["top-100"]["numerator"])
self.assertEqual(1, overview["all"]["numerator"])
self.assertEqual(1, overview["top-20"]["numerator"])
self.assertEqual(1, overview["top-50"]["numerator"])
self.assertEqual(1, overview["top-100"]["numerator"])
# Update the parent and translation to be a template
d = t.document.parent
@ -242,29 +240,29 @@ class L10NOverviewTests(TestCase):
t.document.save()
overview = l10n_overview_rows("de")
eq_(0, overview["all"]["numerator"])
eq_(0, overview["top-20"]["numerator"])
eq_(0, overview["top-50"]["numerator"])
eq_(0, overview["top-100"]["numerator"])
self.assertEqual(0, overview["all"]["numerator"])
self.assertEqual(0, overview["top-20"]["numerator"])
self.assertEqual(0, overview["top-50"]["numerator"])
self.assertEqual(0, overview["top-100"]["numerator"])
def test_by_product(self):
"""Test the product filtering of the overview."""
p = ProductFactory(title="Firefox", slug="firefox")
t = TranslatedRevisionFactory(is_approved=True, document__locale="de")
eq_(0, l10n_overview_rows("de", product=p)["all"]["numerator"])
eq_(0, l10n_overview_rows("de", product=p)["all"]["denominator"])
self.assertEqual(0, l10n_overview_rows("de", product=p)["all"]["numerator"])
self.assertEqual(0, l10n_overview_rows("de", product=p)["all"]["denominator"])
t.document.parent.products.add(p)
eq_(1, l10n_overview_rows("de", product=p)["all"]["numerator"])
eq_(1, l10n_overview_rows("de", product=p)["all"]["denominator"])
self.assertEqual(1, l10n_overview_rows("de", product=p)["all"]["numerator"])
self.assertEqual(1, l10n_overview_rows("de", product=p)["all"]["denominator"])
def test_redirects_are_ignored(self):
"""Verify that redirects aren't counted in the overview."""
TranslatedRevisionFactory(document__locale="de", is_approved=True)
eq_(1, l10n_overview_rows("de")["all"]["numerator"])
self.assertEqual(1, l10n_overview_rows("de")["all"]["numerator"])
# A redirect shouldn't affect any of the tests.
RedirectRevisionFactory(
@ -274,10 +272,10 @@ class L10NOverviewTests(TestCase):
)
overview = l10n_overview_rows("de")
eq_(1, overview["all"]["numerator"])
eq_(1, overview["top-20"]["numerator"])
eq_(1, overview["top-50"]["numerator"])
eq_(1, overview["top-100"]["numerator"])
self.assertEqual(1, overview["all"]["numerator"])
self.assertEqual(1, overview["top-20"]["numerator"])
self.assertEqual(1, overview["top-50"]["numerator"])
self.assertEqual(1, overview["top-100"]["numerator"])
def test_miscounting_archived(self):
"""
@ -301,11 +299,11 @@ class L10NOverviewTests(TestCase):
# so bypass Document.save().
translation2.is_archived = False
ModelBase.save(translation2)
eq_(translation2.is_archived, False)
self.assertEqual(translation2.is_archived, False)
overview = l10n_overview_rows(locale)
eq_(1, overview["all"]["denominator"])
eq_(1, overview["all"]["numerator"])
self.assertEqual(1, overview["all"]["denominator"])
self.assertEqual(1, overview["all"]["numerator"])
class UnreviewedChangesTests(ReadoutTestCase):
@ -350,11 +348,11 @@ class UnreviewedChangesTests(ReadoutTestCase):
)
# There shouldn't be any rows yet.
eq_(0, len(self.rows(product=p)))
self.assertEqual(0, len(self.rows(product=p)))
# Add the product to the parent document, and verify it shows up.
unreviewed.document.parent.products.add(p)
eq_(self.row(product=p)["title"], unreviewed.document.title)
self.assertEqual(self.row(product=p)["title"], unreviewed.document.title)
class MostVisitedDefaultLanguageTests(ReadoutTestCase):
@ -370,16 +368,16 @@ class MostVisitedDefaultLanguageTests(ReadoutTestCase):
ApprovedRevisionFactory(document=d)
# There shouldn't be any rows yet.
eq_(0, len(self.rows(locale=locale, product=p)))
self.assertEqual(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)
self.assertEqual(self.row(locale=locale, product=p)["title"], d.title)
def test_redirects_not_shown(self):
"""Redirects shouldn't appear in Most Visited readout."""
RedirectRevisionFactory(is_ready_for_localization=True)
eq_(0, len(self.titles()))
self.assertEqual(0, len(self.titles()))
class TemplateTests(ReadoutTestCase):
@ -395,9 +393,9 @@ class TemplateTests(ReadoutTestCase):
ApprovedRevisionFactory(document=d)
ApprovedRevisionFactory(document=TemplateDocumentFactory())
eq_(1, len(self.rows(locale=locale, product=p)))
eq_(t.title, self.row(locale=locale, product=p)["title"])
eq_("", self.row(locale=locale, product=p)["status"])
self.assertEqual(1, len(self.rows(locale=locale, product=p)))
self.assertEqual(t.title, self.row(locale=locale, product=p)["title"])
self.assertEqual("", self.row(locale=locale, product=p)["status"])
def test_needs_changes(self):
"""Test status for article that needs changes"""
@ -407,8 +405,8 @@ class TemplateTests(ReadoutTestCase):
row = self.row(locale=locale)
eq_(row["title"], d.title)
eq_(str(row["status"]), "Changes Needed")
self.assertEqual(row["title"], d.title)
self.assertEqual(str(row["status"]), "Changes Needed")
def test_needs_review(self):
"""Test status for article that needs review"""
@ -418,8 +416,8 @@ class TemplateTests(ReadoutTestCase):
row = self.row(locale=locale)
eq_(row["title"], d.title)
eq_(str(row["status"]), "Review Needed")
self.assertEqual(row["title"], d.title)
self.assertEqual(str(row["status"]), "Review Needed")
def test_unready_for_l10n(self):
"""Test status for article that is not ready for l10n"""
@ -432,8 +430,8 @@ class TemplateTests(ReadoutTestCase):
row = self.row(locale=locale)
eq_(row["title"], d.title)
eq_(str(row["status"]), "Changes Not Ready For Localization")
self.assertEqual(row["title"], d.title)
self.assertEqual(str(row["status"]), "Changes Not Ready For Localization")
class HowToContributeTests(ReadoutTestCase):
@ -450,9 +448,9 @@ class HowToContributeTests(ReadoutTestCase):
ApprovedRevisionFactory(document=d1)
ApprovedRevisionFactory(document=d2)
eq_(1, len(self.rows(locale=locale, product=p)))
eq_(d2.title, self.row(locale=locale, product=p)["title"])
eq_("", self.row(locale=locale, product=p)["status"])
self.assertEqual(1, len(self.rows(locale=locale, product=p)))
self.assertEqual(d2.title, self.row(locale=locale, product=p)["title"])
self.assertEqual("", self.row(locale=locale, product=p)["status"])
class AdministrationTests(ReadoutTestCase):
@ -469,9 +467,9 @@ class AdministrationTests(ReadoutTestCase):
ApprovedRevisionFactory(document=d1)
ApprovedRevisionFactory(document=d2)
eq_(1, len(self.rows(locale=locale, product=p)))
eq_(d2.title, self.row(locale=locale, product=p)["title"])
eq_("", self.row(locale=locale, product=p)["status"])
self.assertEqual(1, len(self.rows(locale=locale, product=p)))
self.assertEqual(d2.title, self.row(locale=locale, product=p)["title"])
self.assertEqual("", self.row(locale=locale, product=p)["status"])
class MostVisitedTranslationsTests(ReadoutTestCase):
@ -490,8 +488,8 @@ class MostVisitedTranslationsTests(ReadoutTestCase):
document__locale="de", reviewed=None, is_approved=False
)
row = self.row()
eq_(row["title"], unreviewed.document.title)
eq_(row["status"], "Review Needed")
self.assertEqual(row["title"], unreviewed.document.title)
self.assertEqual(row["status"], "Review Needed")
def test_unlocalizable(self):
"""Unlocalizable docs shouldn't show up in the list."""
@ -512,8 +510,8 @@ class MostVisitedTranslationsTests(ReadoutTestCase):
significance=significance,
)
row = self.row()
eq_(row["title"], translation.document.title)
eq_(row["status"], status)
self.assertEqual(row["title"], translation.document.title)
self.assertEqual(row["status"], status)
def test_out_of_date(self):
"""Assert out-of-date translations are labeled as such."""
@ -527,16 +525,16 @@ class MostVisitedTranslationsTests(ReadoutTestCase):
"""Assert untranslated documents are labeled as such."""
untranslated = ApprovedRevisionFactory(is_ready_for_localization=True)
row = self.row()
eq_(row["title"], untranslated.document.title)
eq_(str(row["status"]), "Translation Needed")
self.assertEqual(row["title"], untranslated.document.title)
self.assertEqual(str(row["status"]), "Translation Needed")
def test_up_to_date(self):
"""Show up-to-date translations have no status, just a happy class."""
translation = TranslatedRevisionFactory(document__locale="de", is_approved=True)
row = self.row()
eq_(row["title"], translation.document.title)
eq_(str(row["status"]), "")
eq_(row["status_class"], "ok")
self.assertEqual(row["title"], translation.document.title)
self.assertEqual(str(row["status"]), "")
self.assertEqual(row["status_class"], "ok")
def test_one_rejected_revision(self):
"""Translation with 1 rejected rev shows as Needs Translation"""
@ -545,12 +543,12 @@ class MostVisitedTranslationsTests(ReadoutTestCase):
)
row = self.row()
eq_(row["status_class"], "untranslated")
self.assertEqual(row["status_class"], "untranslated")
def test_spam(self):
"""Don't offer unapproved (often spam) articles for translation."""
ApprovedRevisionFactory()
eq_([], MostVisitedTranslationsReadout(MockRequest()).rows())
self.assertEqual([], MostVisitedTranslationsReadout(MockRequest()).rows())
def test_consider_max_significance(self):
"""Use max significance for determining change significance
@ -571,8 +569,8 @@ class MostVisitedTranslationsTests(ReadoutTestCase):
significance=MEDIUM_SIGNIFICANCE,
)
row = self.row()
eq_(row["title"], translation.document.title)
eq_(str(row["status"]), "Immediate Update Needed")
self.assertEqual(row["title"], translation.document.title)
self.assertEqual(str(row["status"]), "Immediate Update Needed")
def test_consider_only_approved_significances(self):
"""Consider only approved significances when computing the max."""
@ -590,10 +588,10 @@ class MostVisitedTranslationsTests(ReadoutTestCase):
significance=MEDIUM_SIGNIFICANCE,
)
row = self.row()
eq_(row["title"], translation.document.title)
self.assertEqual(row["title"], translation.document.title)
# This should show as medium significance, because the revision with
# major significance is unapproved:
eq_(str(row["status"]), "Update Needed")
self.assertEqual(str(row["status"]), "Update Needed")
def test_by_product(self):
"""Test the product filtering of the readout."""
@ -602,11 +600,11 @@ class MostVisitedTranslationsTests(ReadoutTestCase):
d = r.document
# There shouldn't be any rows yet.
eq_(0, len(self.rows(product=p)))
self.assertEqual(0, len(self.rows(product=p)))
# Add the product to the parent document, and verify it shows up.
d.parent.products.add(p)
eq_(self.row(product=p)["title"], d.title)
self.assertEqual(self.row(product=p)["title"], d.title)
class TemplateTranslationsTests(ReadoutTestCase):
@ -624,8 +622,8 @@ class TemplateTranslationsTests(ReadoutTestCase):
d = TemplateDocumentFactory()
untranslated = ApprovedRevisionFactory(document=d, is_ready_for_localization=True)
row = self.row()
eq_(row["title"], untranslated.document.title)
eq_(str(row["status"]), "Translation Needed")
self.assertEqual(row["title"], untranslated.document.title)
self.assertEqual(str(row["status"]), "Translation Needed")
def test_by_product(self):
"""Test the product filtering of the readout."""
@ -634,11 +632,11 @@ class TemplateTranslationsTests(ReadoutTestCase):
ApprovedRevisionFactory(document=d, is_ready_for_localization=True)
# There shouldn't be any rows yet.
eq_(0, len(self.rows(product=p)))
self.assertEqual(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)
self.assertEqual(self.row(product=p)["title"], d.title)
class UnreadyTests(ReadoutTestCase):
@ -651,7 +649,7 @@ class UnreadyTests(ReadoutTestCase):
RevisionFactory(
is_approved=False, is_ready_for_localization=False, significance=MAJOR_SIGNIFICANCE
)
eq_([], self.titles())
self.assertEqual([], self.titles())
def test_unapproved_revs(self):
"""Don't show articles with unreviewed or rejected revs after latest"""
@ -663,7 +661,7 @@ class UnreadyTests(ReadoutTestCase):
RevisionFactory(
document=d, is_approved=False, reviewed=datetime.now(), is_ready_for_localization=False
)
eq_([], self.titles())
self.assertEqual([], self.titles())
def test_first_rev(self):
"""If an article's first revision is approved, show the article.
@ -675,7 +673,7 @@ class UnreadyTests(ReadoutTestCase):
r = ApprovedRevisionFactory(
reviewed=datetime.now(), is_ready_for_localization=False, significance=None
)
eq_([r.document.title], self.titles())
self.assertEqual([r.document.title], self.titles())
def test_insignificant_revs(self):
# Articles with approved, unready, but insignificant revisions
@ -687,7 +685,7 @@ class UnreadyTests(ReadoutTestCase):
is_ready_for_localization=False,
significance=TYPO_SIGNIFICANCE,
)
eq_([], self.titles())
self.assertEqual([], self.titles())
def test_significant_revs(self):
# Articles with approved, significant, but unready revisions
@ -698,7 +696,7 @@ class UnreadyTests(ReadoutTestCase):
is_ready_for_localization=False,
significance=MEDIUM_SIGNIFICANCE,
)
eq_([ready.document.title], self.titles())
self.assertEqual([ready.document.title], self.titles())
def test_by_product(self):
"""Test the product filtering of the readout."""
@ -711,11 +709,11 @@ class UnreadyTests(ReadoutTestCase):
)
# There shouldn't be any rows yet.
eq_(0, len(self.rows(product=p)))
self.assertEqual(0, len(self.rows(product=p)))
# Add the product to the document, and verify it shows up.
ready.document.products.add(p)
eq_(self.row(product=p)["title"], ready.document.title)
self.assertEqual(self.row(product=p)["title"], ready.document.title)
class NeedsChangesTests(ReadoutTestCase):
@ -730,7 +728,7 @@ class NeedsChangesTests(ReadoutTestCase):
)
RevisionFactory(document=document)
titles = self.titles()
eq_(1, len(titles))
self.assertEqual(1, len(titles))
assert document.title in titles
def test_by_product(self):
@ -742,11 +740,11 @@ class NeedsChangesTests(ReadoutTestCase):
RevisionFactory(document=d)
# There shouldn't be any rows yet.
eq_(0, len(self.rows(product=p)))
self.assertEqual(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)
self.assertEqual(self.row(product=p)["title"], d.title)
class CannedResponsesTests(ReadoutTestCase):
@ -757,13 +755,13 @@ class CannedResponsesTests(ReadoutTestCase):
ApprovedRevisionFactory(
is_ready_for_localization=True, document__category=CANNED_RESPONSES_CATEGORY
)
eq_(1, len(self.rows()))
self.assertEqual(1, len(self.rows()))
def test_translation_state(self):
eng_doc = DocumentFactory(category=CANNED_RESPONSES_CATEGORY)
eng_rev = ApprovedRevisionFactory(is_ready_for_localization=True, document=eng_doc)
eq_("untranslated", self.row()["status_class"])
self.assertEqual("untranslated", self.row()["status_class"])
# Now translate it, but don't approve
de_doc = DocumentFactory(category=CANNED_RESPONSES_CATEGORY, parent=eng_doc, locale="de")
@ -771,27 +769,27 @@ class CannedResponsesTests(ReadoutTestCase):
document=de_doc, based_on=eng_rev, is_approved=False, reviewed=None
)
eq_("review", self.row()["status_class"])
self.assertEqual("review", self.row()["status_class"])
# Approve it, so now every this is ok.
de_rev.is_approved = True
de_rev.save()
eq_("ok", self.row()["status_class"])
self.assertEqual("ok", self.row()["status_class"])
# Now update the parent, so it becomes minorly out of date
ApprovedRevisionFactory(
is_ready_for_localization=True, document=eng_doc, significance=MEDIUM_SIGNIFICANCE
)
eq_("update", self.row()["status_class"])
self.assertEqual("update", self.row()["status_class"])
# Now update the parent, so it becomes majorly out of date
ApprovedRevisionFactory(
is_ready_for_localization=True, document=eng_doc, significance=MAJOR_SIGNIFICANCE
)
eq_("out-of-date", self.row()["status_class"])
self.assertEqual("out-of-date", self.row()["status_class"])
def test_by_product(self):
"""Test the product filtering of the readout."""
@ -800,9 +798,9 @@ class CannedResponsesTests(ReadoutTestCase):
ApprovedRevisionFactory(document=d, is_ready_for_localization=True)
# There shouldn't be any rows yet.
eq_(0, len(self.rows(product=p)))
self.assertEqual(0, len(self.rows(product=p)))
# Add the product to the document, and verify it shows up.
d.products.add(p)
eq_(1, len(self.rows(product=p)))
eq_(self.row(product=p)["title"], d.title)
self.assertEqual(1, len(self.rows(product=p)))
self.assertEqual(self.row(product=p)["title"], d.title)

Просмотреть файл

@ -1,4 +1,3 @@
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.sumo.tests import TestCase
@ -31,21 +30,21 @@ class LocalizationDashTests(TestCase):
)
response = self.client.get(reverse("dashboards.localization", locale="de"), follow=False)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
self._assert_readout_contains(doc, "unreviewed", unreviewed.document.title)
def test_show_volunteer_button_for_anon(self):
resp = self.client.get(reverse("dashboards.localization", locale="es"))
eq_(200, resp.status_code)
self.assertEqual(200, resp.status_code)
resp_content = pq(resp.content)
eq_(1, len(resp_content("#get-involved-box")))
eq_(1, len(resp_content("#get-involved-box .button")))
self.assertEqual(1, len(resp_content("#get-involved-box")))
self.assertEqual(1, len(resp_content("#get-involved-box .button")))
def test_hide_volunteer_button_for_authed(self):
u1 = UserFactory()
self.client.login(username=u1.username, password="testpass")
resp = self.client.get(reverse("dashboards.localization", locale="es"))
eq_(200, resp.status_code)
self.assertEqual(200, resp.status_code)
resp_content = pq(resp.content)
eq_(0, len(resp_content("#get-involved-box")))
self.assertEqual(0, len(resp_content("#get-involved-box")))

Просмотреть файл

@ -1,7 +1,5 @@
from datetime import date
from unittest.mock import patch
from nose.tools import eq_
from kitsune.dashboards import utils
from kitsune.dashboards.utils import get_locales_by_visit
@ -22,7 +20,7 @@ class DashboardUtilsTests(TestCase):
}
results = get_locales_by_visit(date(2013, 7, 1), date(2013, 8, 1))
eq_(
self.assertEqual(
[
("en-US", 9381226),
("de", 1674352),

Просмотреть файл

@ -1,14 +1,12 @@
from datetime import timedelta, datetime
from nose.tools import eq_
from datetime import datetime, timedelta
from kitsune.announcements.tests import AnnouncementFactory
from kitsune.dashboards.readouts import CONTRIBUTOR_READOUTS
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
from kitsune.users.tests import UserFactory
from kitsune.wiki.models import HelpfulVote, Document
from kitsune.wiki.tests import LocaleFactory, ApprovedRevisionFactory
from kitsune.wiki.models import Document, HelpfulVote
from kitsune.wiki.tests import ApprovedRevisionFactory, LocaleFactory
class LocalizationDashTests(TestCase):
@ -63,7 +61,7 @@ class ContributorDashTests(TestCase):
def test_main_view(self):
"""Assert the top page of the contributor dash resolves, renders."""
response = self.client.get(reverse("dashboards.contributors", locale="en-US"))
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_detail_view(self):
"""Assert the detail page of the contributor dash resolves, renders."""
@ -75,7 +73,7 @@ class ContributorDashTests(TestCase):
locale="en-US",
)
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_needs_change_comment_is_shown(self):
# If there are already 10 documents, this is probably going to
@ -89,7 +87,7 @@ class ContributorDashTests(TestCase):
)
response = self.client.get(reverse("dashboards.contributors", locale="en-US"))
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
assert change_comment in response.content

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.flagit.models import FlaggedObject
from kitsune.flagit.tests import TestCaseBase
from kitsune.sumo.urlresolvers import reverse
@ -16,12 +14,12 @@ class FlagitTestPermissions(TestCaseBase):
def test_permission_required(self):
url = reverse("flagit.queue", force_locale=True)
resp = self.client.get(url)
eq_(302, resp.status_code)
self.assertEqual(302, resp.status_code)
self.client.login(username=self.user.username, password="testpass")
resp = self.client.get(url)
eq_(403, resp.status_code)
self.assertEqual(403, resp.status_code)
add_permission(self.user, FlaggedObject, "can_moderate")
resp = self.client.get(url)
eq_(200, resp.status_code)
self.assertEqual(200, resp.status_code)

Просмотреть файл

@ -1,11 +1,10 @@
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.flagit.models import FlaggedObject
from kitsune.flagit.tests import TestCaseBase
from kitsune.questions.models import Answer
from kitsune.questions.tests import AnswerFactory
from kitsune.sumo.tests import post, get
from kitsune.sumo.tests import get, post
from kitsune.users.tests import UserFactory, add_permission
@ -36,10 +35,10 @@ class FlaggedQueueTestCase(TestCaseBase):
# Verify number of flagged objects
response = get(self.client, "flagit.queue")
doc = pq(response.content)
eq_(num_answers, len(doc("#flagged-queue li")))
self.assertEqual(num_answers, len(doc("#flagged-queue li")))
# Reject one flag
flag = FlaggedObject.objects.all()[0]
response = post(self.client, "flagit.update", {"status": 2}, args=[flag.id])
doc = pq(response.content)
eq_(num_answers - 1, len(doc("#flagged-queue li")))
self.assertEqual(num_answers - 1, len(doc("#flagged-queue li")))

Просмотреть файл

@ -1,9 +1,7 @@
from django.contrib.contenttypes.models import ContentType
from nose.tools import eq_
from kitsune.flagit.tests import TestCaseBase
from kitsune.flagit.models import FlaggedObject
from kitsune.flagit.tests import TestCaseBase
from kitsune.questions.models import Question
from kitsune.questions.tests import QuestionFactory
from kitsune.sumo.tests import post
@ -33,9 +31,9 @@ class FlagTestCase(TestCaseBase):
"next": self.question.get_absolute_url(),
}
post(self.client, "flagit.flag", d)
eq_(1, FlaggedObject.objects.count())
self.assertEqual(1, FlaggedObject.objects.count())
flag = FlaggedObject.objects.all()[0]
eq_(self.user.username, flag.creator.username)
eq_("spam", flag.reason)
eq_(self.question, flag.content_object)
self.assertEqual(self.user.username, flag.creator.username)
self.assertEqual("spam", flag.reason)
self.assertEqual(self.question, flag.content_object)

Просмотреть файл

@ -1,15 +1,13 @@
from datetime import datetime
import factory
from django.contrib.contenttypes.models import ContentType
from django.template.defaultfilters import slugify
import factory
from nose.tools import eq_
from kitsune.access.tests import PermissionFactory
from kitsune.forums.models import Forum, Thread, Post
from kitsune.users.tests import UserFactory
from kitsune.forums.models import Forum, Post, Thread
from kitsune.sumo.tests import FuzzyUnicode, LocalizingClient, TestCase
from kitsune.users.tests import UserFactory
class ForumTestCase(TestCase):
@ -66,16 +64,16 @@ class ThreadFactory(factory.django.DjangoModelFactory):
class ThreadFactoryTests(TestCase):
def test_has_one_post(self):
t = ThreadFactory()
eq_(t.post_set.count(), 1)
self.assertEqual(t.post_set.count(), 1)
def test_can_set_post_properties(self):
t = ThreadFactory(posts__content="lol")
eq_(t.post_set.get().content, "lol")
self.assertEqual(t.post_set.get().content, "lol")
def test_can_set_posts(self):
t = ThreadFactory(posts=[{"content": "one"}, {"content": "two"}])
contents = list(t.post_set.values_list("content", flat=True))
eq_(contents, ["one", "two"])
self.assertEqual(contents, ["one", "two"])
def test_posts_belong_to_the_thread(self):
t = ThreadFactory()

Просмотреть файл

@ -1,12 +1,11 @@
from datetime import datetime, timedelta
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.forums.feeds import ThreadsFeed, PostsFeed
from kitsune.forums.tests import ForumTestCase, ForumFactory, ThreadFactory, PostFactory
from kitsune.forums.feeds import PostsFeed, ThreadsFeed
from kitsune.forums.tests import ForumFactory, ForumTestCase, PostFactory, ThreadFactory
from kitsune.sumo.tests import get
YESTERDAY = datetime.now() - timedelta(days=1)
@ -21,7 +20,7 @@ class ForumTestFeedSorting(ForumTestCase):
ThreadFactory(forum=f, created=YESTERDAY)
t2 = ThreadFactory(forum=f)
eq_(t2.id, ThreadsFeed().items(f)[0].id)
self.assertEqual(t2.id, ThreadsFeed().items(f)[0].id)
def test_posts_sort(self):
"""Ensure that posts are being sorted properly by date/time."""
@ -31,7 +30,7 @@ class ForumTestFeedSorting(ForumTestCase):
p = PostFactory(thread=t, created=now)
# The newest post should be the first one listed.
eq_(p.id, PostsFeed().items(t)[0].id)
self.assertEqual(p.id, PostsFeed().items(t)[0].id)
def test_multi_feed_titling(self):
"""Ensure that titles are being applied properly to feeds."""
@ -41,6 +40,6 @@ class ForumTestFeedSorting(ForumTestCase):
response = get(self.client, "forums.threads", args=[forum.slug])
doc = pq(response.content)
eq_(
self.assertEqual(
ThreadsFeed().title(forum), doc('link[type="application/atom+xml"]')[0].attrib["title"]
)

Просмотреть файл

@ -1,7 +1,6 @@
from datetime import datetime, timedelta
from django.contrib.contenttypes.models import ContentType
from nose.tools import eq_
from kitsune.access.tests import PermissionFactory
from kitsune.flagit.models import FlaggedObject
@ -20,12 +19,12 @@ class ForumModelTestCase(ForumTestCase):
def test_forum_absolute_url(self):
f = ForumFactory()
eq_("/forums/%s/" % f.slug, f.get_absolute_url())
self.assertEqual("/forums/%s/" % f.slug, f.get_absolute_url())
def test_thread_absolute_url(self):
t = ThreadFactory()
eq_("/forums/%s/%s" % (t.forum.slug, t.id), t.get_absolute_url())
self.assertEqual("/forums/%s/%s" % (t.forum.slug, t.id), t.get_absolute_url())
def test_post_absolute_url(self):
t = ThreadFactory(posts=[])
@ -39,13 +38,13 @@ class ForumModelTestCase(ForumTestCase):
url = reverse(
"forums.posts", kwargs={"forum_slug": p1.thread.forum.slug, "thread_id": p1.thread.id}
)
eq_(urlparams(url, hash="post-%s" % p1.id), p1.get_absolute_url())
self.assertEqual(urlparams(url, hash="post-%s" % p1.id), p1.get_absolute_url())
url = reverse(
"forums.posts", kwargs={"forum_slug": p2.thread.forum.slug, "thread_id": p2.thread.id}
)
exp_ = urlparams(url, hash="post-%s" % p2.id, page=2)
eq_(exp_, p2.get_absolute_url())
self.assertEqual(exp_, p2.get_absolute_url())
def test_post_page(self):
t = ThreadFactory()
@ -55,8 +54,8 @@ class ForumModelTestCase(ForumTestCase):
p2 = PostFactory(thread=t)
for p in page1:
eq_(1, p.page)
eq_(2, p2.page)
self.assertEqual(1, p.page)
self.assertEqual(2, p2.page)
def test_delete_post_removes_flag(self):
"""Deleting a post also removes the flags on that post."""
@ -66,10 +65,10 @@ class ForumModelTestCase(ForumTestCase):
FlaggedObject.objects.create(
status=0, content_object=p, reason="language", creator_id=u.id
)
eq_(1, FlaggedObject.objects.count())
self.assertEqual(1, FlaggedObject.objects.count())
p.delete()
eq_(0, FlaggedObject.objects.count())
self.assertEqual(0, FlaggedObject.objects.count())
def test_thread_last_post_url(self):
t = ThreadFactory()
@ -91,15 +90,15 @@ class ForumModelTestCase(ForumTestCase):
new_post = PostFactory(thread=t, content="test")
f = Forum.objects.get(id=t.forum_id)
t = Thread.objects.get(id=t.id)
eq_(f.last_post.id, new_post.id)
eq_(t.last_post.id, new_post.id)
self.assertEqual(f.last_post.id, new_post.id)
self.assertEqual(t.last_post.id, new_post.id)
# delete the new post, then check that last_post is updated
new_post.delete()
f = Forum.objects.get(id=f.id)
t = Thread.objects.get(id=t.id)
eq_(f.last_post.id, orig_post.id)
eq_(t.last_post.id, orig_post.id)
self.assertEqual(f.last_post.id, orig_post.id)
self.assertEqual(t.last_post.id, orig_post.id)
def test_public_access(self):
# Assert Forums think they're publicly viewable and postable
@ -144,8 +143,8 @@ class ForumModelTestCase(ForumTestCase):
p3 = PostFactory(thread=t3, created=YESTERDAY)
# Verify the last_post's are correct.
eq_(p2, Forum.objects.get(id=old_forum.id).last_post)
eq_(p3, Forum.objects.get(id=new_forum.id).last_post)
self.assertEqual(p2, Forum.objects.get(id=old_forum.id).last_post)
self.assertEqual(p3, Forum.objects.get(id=new_forum.id).last_post)
# Move the t2 thread.
t2 = Thread.objects.get(id=t2.id)
@ -153,15 +152,15 @@ class ForumModelTestCase(ForumTestCase):
t2.save()
# Old forum's last_post updated?
eq_(p1.id, Forum.objects.get(id=old_forum.id).last_post_id)
self.assertEqual(p1.id, Forum.objects.get(id=old_forum.id).last_post_id)
# New forum's last_post updated?
eq_(p2.id, Forum.objects.get(id=new_forum.id).last_post_id)
self.assertEqual(p2.id, Forum.objects.get(id=new_forum.id).last_post_id)
# Delete the post, and both forums should still exist:
p2.delete()
eq_(1, Forum.objects.filter(id=old_forum.id).count())
eq_(1, Forum.objects.filter(id=new_forum.id).count())
self.assertEqual(1, Forum.objects.filter(id=old_forum.id).count())
self.assertEqual(1, Forum.objects.filter(id=new_forum.id).count())
def test_delete_removes_watches(self):
f = ForumFactory()
@ -175,12 +174,12 @@ class ForumModelTestCase(ForumTestCase):
# Create a post and verify it is the last one in the forum.
post = PostFactory(content="test")
forum = post.thread.forum
eq_(forum.last_post.id, post.id)
self.assertEqual(forum.last_post.id, post.id)
# Delete the post creator, then check the forum still exists
post.author.delete()
forum = Forum.objects.get(id=forum.id)
eq_(forum.last_post, None)
self.assertEqual(forum.last_post, None)
class ThreadModelTestCase(ForumTestCase):
@ -195,13 +194,13 @@ class ThreadModelTestCase(ForumTestCase):
t = ThreadFactory(title="test", forum=f, posts=[])
p = PostFactory(thread=t, content="test", author=t.creator)
f = Forum.objects.get(id=f.id)
eq_(f.last_post.id, p.id)
self.assertEqual(f.last_post.id, p.id)
# delete the post, verify last_post updated
t.delete()
f = Forum.objects.get(id=f.id)
eq_(f.last_post.id, last_post.id)
eq_(Thread.objects.filter(pk=t.id).count(), 0)
self.assertEqual(f.last_post.id, last_post.id)
self.assertEqual(Thread.objects.filter(pk=t.id).count(), 0)
def test_delete_removes_watches(self):
t = ThreadFactory()
@ -213,9 +212,9 @@ class ThreadModelTestCase(ForumTestCase):
def test_delete_last_and_only_post_in_thread(self):
"""Deleting the only post in a thread should delete the thread"""
t = ThreadFactory()
eq_(1, t.post_set.count())
self.assertEqual(1, t.post_set.count())
t.delete()
eq_(0, Thread.objects.filter(pk=t.id).count())
self.assertEqual(0, Thread.objects.filter(pk=t.id).count())
class SaveDateTestCase(ForumTestCase):
@ -249,7 +248,7 @@ class SaveDateTestCase(ForumTestCase):
# respect that created date.
created = datetime(1992, 1, 12, 9, 48, 23)
t = Thread(forum=self.forum, title="foo", creator=self.user, created=created)
eq_(created, t.created)
self.assertEqual(created, t.created)
def test_save_old_thread_created(self):
"""Saving an old thread should not change its created date."""
@ -261,7 +260,7 @@ class SaveDateTestCase(ForumTestCase):
t.title = "new title"
t.save()
t = Thread.objects.get(id=t.id)
eq_(created, t.created)
self.assertEqual(created, t.created)
def test_save_new_post_no_timestamps(self):
# Saving a new post should behave as if auto_add_now was set on
@ -277,7 +276,7 @@ class SaveDateTestCase(ForumTestCase):
updated = datetime(2010, 5, 4, 14, 4, 31)
p = PostFactory(thread=self.thread, created=created, updated=updated)
eq_(updated, p.updated)
self.assertEqual(updated, p.updated)
p.content = "baz"
p.updated_by = self.user
@ -285,7 +284,7 @@ class SaveDateTestCase(ForumTestCase):
now = datetime.now()
self.assertDateTimeAlmostEqual(now, p.updated, self.delta)
eq_(created, p.created)
self.assertEqual(created, p.created)
def test_save_new_post_timestamps(self):
# Saving a new post should allow you to override auto_add_now-
@ -295,10 +294,10 @@ class SaveDateTestCase(ForumTestCase):
thread=self.thread, content="bar", author=self.user, created=created_, updated=created_
)
p.save()
eq_(created_, p.created)
eq_(created_, p.updated)
self.assertEqual(created_, p.created)
self.assertEqual(created_, p.updated)
def test_content_parsed_sanity(self):
"""The content_parsed field is populated."""
p = PostFactory(thread=self.thread, content="yet another post")
eq_("<p>yet another post\n</p>", p.content_parsed)
self.assertEqual("<p>yet another post\n</p>", p.content_parsed)

Просмотреть файл

@ -1,3 +1,5 @@
from unittest import mock
from django.contrib import admin
from django.contrib.admin.options import ModelAdmin
from django.contrib.auth.models import User
@ -5,18 +7,14 @@ from django.contrib.sites.models import Site
from django.core import mail
from django.test.client import RequestFactory
from unittest import mock
from nose.tools import eq_
from kitsune.forums.events import NewPostEvent, NewThreadEvent
from kitsune.forums.models import Thread, Post
from kitsune.forums.tests import ForumTestCase, ThreadFactory, ForumFactory, PostFactory
from kitsune.forums.models import Post, Thread
from kitsune.forums.tests import ForumFactory, ForumTestCase, PostFactory, ThreadFactory
from kitsune.sumo.tests import attrs_eq, post, starts_with
from kitsune.sumo.urlresolvers import reverse
from kitsune.sumo.tests import post, attrs_eq, starts_with
from kitsune.users.models import Setting
from kitsune.users.tests import UserFactory
# Some of these contain a locale prefix on included links, while
# others don't. This depends on whether the tests use them inside or
# outside the scope of a request. See the long explanation in
@ -266,7 +264,7 @@ class NotificationsTests(ForumTestCase):
self.client.login(username=poster.username, password="testpass")
post(self.client, "forums.reply", {"content": "a post"}, args=[f.slug, t.id])
eq_(1, len(mail.outbox))
self.assertEqual(1, len(mail.outbox))
p = Post.objects.all().order_by("-id")[0]
attrs_eq(mail.outbox[0], to=[watcher.email], subject="Re: {f} - {t}".format(f=f, t=t))
body = REPLY_EMAIL.format(

Просмотреть файл

@ -2,10 +2,8 @@ from datetime import datetime, timedelta
from django.conf import settings
from nose.tools import eq_, raises
from kitsune.forums.models import Thread, Forum, ThreadLockedError
from kitsune.forums.tests import ForumTestCase, ThreadFactory, PostFactory
from kitsune.forums.models import Forum, Thread, ThreadLockedError
from kitsune.forums.tests import ForumTestCase, PostFactory, ThreadFactory
from kitsune.forums.views import sort_threads
from kitsune.sumo.tests import get
from kitsune.users.tests import UserFactory
@ -20,7 +18,7 @@ class PostTestCase(ForumTestCase):
p = t.new_post(author=t.creator, content="an update")
p.save()
t = Thread.objects.get(id=t.id)
eq_(p.id, t.last_post_id)
self.assertEqual(p.id, t.last_post_id)
def test_new_post_updates_forum(self):
# Saving a new post should update the last_post key in the
@ -30,7 +28,7 @@ class PostTestCase(ForumTestCase):
p = t.new_post(author=t.creator, content="another update")
p.save()
f = Forum.objects.get(id=t.forum_id)
eq_(p.id, f.last_post_id)
self.assertEqual(p.id, f.last_post_id)
def test_update_post_does_not_update_thread(self):
# Updating/saving an old post in a thread should _not_ update
@ -40,7 +38,7 @@ class PostTestCase(ForumTestCase):
last = PostFactory(thread=t)
old.content = "updated content"
old.save()
eq_(last.id, old.thread.last_post_id)
self.assertEqual(last.id, old.thread.last_post_id)
def test_update_forum_does_not_update_thread(self):
# Updating/saving an old post in a forum should _not_ update
@ -50,16 +48,16 @@ class PostTestCase(ForumTestCase):
last = PostFactory(thread=t)
old.content = "updated content"
old.save()
eq_(last.id, t.forum.last_post_id)
self.assertEqual(last.id, t.forum.last_post_id)
def test_replies_count(self):
# The Thread.replies value should remain one less than the
# number of posts in the thread.
t = ThreadFactory(posts=[{}, {}, {}])
old = t.replies
eq_(2, old)
self.assertEqual(2, old)
t.new_post(author=t.creator, content="test").save()
eq_(old + 1, t.replies)
self.assertEqual(old + 1, t.replies)
def test_sticky_threads_first(self):
# Sticky threads should come before non-sticky threads.
@ -68,7 +66,7 @@ class PostTestCase(ForumTestCase):
sticky = ThreadFactory(forum=t.forum, is_sticky=True, posts=[{"created": yesterday}])
# The older sticky thread shows up first.
eq_(sticky.id, Thread.objects.all()[0].id)
self.assertEqual(sticky.id, Thread.objects.all()[0].id)
def test_thread_sorting(self):
# After the sticky threads, threads should be sorted by the
@ -123,15 +121,15 @@ class PostTestCase(ForumTestCase):
) # Test off-by-one error, high
for replies, pages in test_data:
t.replies = replies
eq_(t.last_page, pages)
self.assertEqual(t.last_page, pages)
@raises(ThreadLockedError)
def test_locked_thread(self):
"""Trying to reply to a locked thread should raise an exception."""
locked = ThreadFactory(is_locked=True)
user = UserFactory()
# This should raise an exception
locked.new_post(author=user, content="empty")
with self.assertRaises(ThreadLockedError):
locked = ThreadFactory(is_locked=True)
user = UserFactory()
# This should raise an exception
locked.new_post(author=user, content="empty")
def test_unlocked_thread(self):
unlocked = ThreadFactory()
@ -142,7 +140,7 @@ class PostTestCase(ForumTestCase):
def test_post_no_session(self):
r = get(self.client, "forums.new_thread", kwargs={"forum_slug": "test-forum"})
assert settings.LOGIN_URL in r.redirect_chain[0][0]
eq_(302, r.redirect_chain[0][1])
self.assertEqual(302, r.redirect_chain[0][1])
class ThreadTestCase(ForumTestCase):
@ -154,4 +152,4 @@ class ThreadTestCase(ForumTestCase):
kwargs={"forum_slug": "test-forum", "thread_id": 1},
)
assert settings.LOGIN_URL in r.redirect_chain[0][0]
eq_(302, r.redirect_chain[0][1])
self.assertEqual(302, r.redirect_chain[0][1])

Просмотреть файл

@ -1,6 +1,5 @@
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from nose.tools import eq_
from kitsune.access.tests import PermissionFactory
from kitsune.forums.models import Post
@ -21,7 +20,7 @@ class PostsTemplateTests(ForumTestCase):
doc = pq(response.content)
error_msg = doc("ul.errorlist li a")[0]
eq_(error_msg.text, "Please provide a message.")
self.assertEqual(error_msg.text, "Please provide a message.")
def test_edit_post_errors(self):
"""Changing post content works."""
@ -39,7 +38,7 @@ class PostsTemplateTests(ForumTestCase):
doc = pq(response.content)
errors = doc("ul.errorlist li a")
eq_(
self.assertEqual(
errors[0].text,
"Your message is too short (4 characters). " + "It must be at least 5 characters.",
)
@ -57,7 +56,7 @@ class PostsTemplateTests(ForumTestCase):
)
doc = pq(res.content)
eq_(len(doc("form.edit-post")), 1)
self.assertEqual(len(doc("form.edit-post")), 1)
def test_edit_post(self):
"""Changing post content works."""
@ -74,15 +73,15 @@ class PostsTemplateTests(ForumTestCase):
)
edited_p = Post.objects.get(id=p.id)
eq_("Some new content", edited_p.content)
self.assertEqual("Some new content", edited_p.content)
def test_posts_fr(self):
"""Posts render for [fr] locale."""
t = ThreadFactory()
response = get(self.client, "forums.posts", args=[t.forum.slug, t.id], locale="fr")
eq_(200, response.status_code)
eq_(
self.assertEqual(200, response.status_code)
self.assertEqual(
"{c}/fr/forums/{f}/{t}".format(c=settings.CANONICAL_URL, f=t.forum.slug, t=t.id),
pq(response.content)('link[rel="canonical"]')[0].attrib["href"],
)
@ -96,7 +95,7 @@ class PostsTemplateTests(ForumTestCase):
# response = get(self.client, "forums.posts", args=[t.forum.slug, t.id])
# doc = pq(response.content)
# crumb = doc("#breadcrumbs li:last-child")
# eq_(crumb.text(), "A thread with a very very very very...")
# self.assertEqual(crumb.text(), "A thread with a very very very very...")
def test_edit_post_moderator(self):
"""Editing post as a moderator works."""
@ -125,10 +124,10 @@ class PostsTemplateTests(ForumTestCase):
{"content": "More new content"},
args=[f.slug, t.id, p.id],
)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
edited_p = Post.objects.get(pk=p.pk)
eq_("More new content", edited_p.content)
self.assertEqual("More new content", edited_p.content)
def test_preview_reply(self):
"""Preview a reply."""
@ -143,10 +142,10 @@ class PostsTemplateTests(ForumTestCase):
{"content": content, "preview": "any string"},
args=[t.forum.slug, t.id],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(content, doc("#post-preview div.content").text())
eq_(1, t.post_set.count())
self.assertEqual(content, doc("#post-preview div.content").text())
self.assertEqual(1, t.post_set.count())
def test_watch_thread(self):
"""Watch and unwatch a thread."""
@ -202,21 +201,21 @@ class PostsTemplateTests(ForumTestCase):
response = get(self.client, "forums.posts", args=[f.slug, t.pk])
doc = pq(response.content)
eq_("nofollow", doc("ol.posts div.content a")[0].attrib["rel"])
self.assertEqual("nofollow", doc("ol.posts div.content a")[0].attrib["rel"])
def test_num_replies(self):
"""Verify the number of replies label."""
t = ThreadFactory()
response = get(self.client, "forums.posts", args=[t.forum.slug, t.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
assert b"0 Replies" in response.content
PostFactory(thread=t)
PostFactory(thread=t)
response = get(self.client, "forums.posts", args=[t.forum.slug, t.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
assert b"2 Replies" in response.content
def test_youtube_in_post(self):
@ -246,7 +245,7 @@ class ThreadsTemplateTests(ForumTestCase):
doc = pq(response.content)
last_post_link = doc(".threads .last-post a:not(.username)")[0]
href = last_post_link.attrib["href"]
eq_(href.split("#")[1], "post-%s" % last.id)
self.assertEqual(href.split("#")[1], "post-%s" % last.id)
def test_empty_thread_errors(self):
"""Posting an empty thread shows errors."""
@ -262,8 +261,8 @@ class ThreadsTemplateTests(ForumTestCase):
)
doc = pq(response.content)
errors = doc("ul.errorlist li a")
eq_(errors[0].text, "Please provide a title.")
eq_(errors[1].text, "Please provide a message.")
self.assertEqual(errors[0].text, "Please provide a title.")
self.assertEqual(errors[1].text, "Please provide a message.")
def test_new_short_thread_errors(self):
"""Posting a short new thread shows errors."""
@ -280,11 +279,11 @@ class ThreadsTemplateTests(ForumTestCase):
doc = pq(response.content)
errors = doc("ul.errorlist li a")
eq_(
self.assertEqual(
errors[0].text,
"Your title is too short (4 characters). " + "It must be at least 5 characters.",
)
eq_(
self.assertEqual(
errors[1].text,
"Your message is too short (4 characters). " + "It must be at least 5 characters.",
)
@ -304,7 +303,7 @@ class ThreadsTemplateTests(ForumTestCase):
doc = pq(response.content)
errors = doc("ul.errorlist li a")
eq_(
self.assertEqual(
errors[0].text,
"Your title is too short (4 characters). " + "It must be at least 5 characters.",
)
@ -318,7 +317,7 @@ class ThreadsTemplateTests(ForumTestCase):
res = get(self.client, "forums.edit_thread", args=[t.forum.slug, t.id])
doc = pq(res.content)
eq_(len(doc("form.edit-thread")), 1)
self.assertEqual(len(doc("form.edit-thread")), 1)
def test_watch_forum(self):
"""Watch and unwatch a forum."""
@ -338,7 +337,7 @@ class ThreadsTemplateTests(ForumTestCase):
f = ForumFactory()
response = get(self.client, "forums.threads", args=[f.slug])
eq_(
self.assertEqual(
"%s/en-US/forums/%s/" % (settings.CANONICAL_URL, f.slug),
pq(response.content)('link[rel="canonical"]')[0].attrib["href"],
)
@ -375,7 +374,7 @@ class ForumsTemplateTests(ForumTestCase):
doc = pq(response.content)
last_post_link = doc(".forums .last-post a:not(.username)")[0]
href = last_post_link.attrib["href"]
eq_(href.split("#")[1], "post-%s" % p.id)
self.assertEqual(href.split("#")[1], "post-%s" % p.id)
def test_restricted_is_invisible(self):
"""Forums with restricted view_in permission shouldn't show up."""
@ -393,7 +392,7 @@ class ForumsTemplateTests(ForumTestCase):
def test_canonical_url(self):
response = get(self.client, "forums.forums")
eq_(
self.assertEqual(
"{}/en-US/forums/".format(settings.CANONICAL_URL),
pq(response.content)('link[rel="canonical"]')[0].attrib["href"],
)
@ -405,18 +404,18 @@ class ForumsTemplateTests(ForumTestCase):
# forum1 should be listed first
r = get(self.client, "forums.forums")
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(forum1.name, doc(".forums tr a").first().text())
self.assertEqual(forum1.name, doc(".forums tr a").first().text())
forum1.display_order = 3
forum1.save()
# forum2 should be listed first
r = get(self.client, "forums.forums")
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(forum2.name, doc(".forums tr a").first().text())
self.assertEqual(forum2.name, doc(".forums tr a").first().text())
def test_is_listed(self):
"""Verify is_listed is respected."""
@ -425,19 +424,19 @@ class ForumsTemplateTests(ForumTestCase):
# Both forums should be listed.
r = get(self.client, "forums.forums")
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(2, len(doc(".forums tr")))
self.assertEqual(2, len(doc(".forums tr")))
forum1.is_listed = False
forum1.save()
# Only forum2 should be listed.
r = get(self.client, "forums.forums")
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(1, len(doc(".forums tr")))
eq_(forum2.name, doc(".forums tr a").text())
self.assertEqual(1, len(doc(".forums tr")))
self.assertEqual(forum2.name, doc(".forums tr a").text())
class NewThreadTemplateTests(ForumTestCase):
@ -454,7 +453,7 @@ class NewThreadTemplateTests(ForumTestCase):
{"title": "Topic", "content": content, "preview": "any string"},
args=[f.slug],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(content, doc("#post-preview div.content").text())
eq_(0, f.thread_set.count()) # No thread was created.
self.assertEqual(content, doc("#post-preview div.content").text())
self.assertEqual(0, f.thread_set.count()) # No thread was created.

Просмотреть файл

@ -1,11 +1,9 @@
from django.contrib.contenttypes.models import ContentType
from nose.tools import eq_
from kitsune.access.tests import PermissionFactory
from kitsune.forums.tests import ForumTestCase, ForumFactory, ThreadFactory, PostFactory
from kitsune.forums.tests import ForumFactory, ForumTestCase, PostFactory, ThreadFactory
from kitsune.sumo.tests import get, post
from kitsune.users.tests import UserFactory, GroupFactory
from kitsune.users.tests import GroupFactory, UserFactory
class BelongsTestCase(ForumTestCase):
@ -19,7 +17,7 @@ class BelongsTestCase(ForumTestCase):
t = ThreadFactory() # Thread belongs to a different forum
r = get(self.client, "forums.posts", args=[f.slug, t.id])
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
u = r.redirect_chain[0][0]
assert u.endswith(t.get_absolute_url())
@ -31,7 +29,7 @@ class BelongsTestCase(ForumTestCase):
self.client.login(username=u.username, password="testpass")
r = post(self.client, "forums.reply", {}, args=[f.slug, t.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_locked_thread_belongs_to_forum(self):
"""Lock action - thread belongs to forum."""
@ -55,7 +53,7 @@ class BelongsTestCase(ForumTestCase):
self.client.login(username=u.username, password="testpass")
r = post(self.client, "forums.lock_thread", {}, args=[f.slug, t.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_sticky_thread_belongs_to_forum(self):
"""Sticky action - thread belongs to forum."""
@ -79,7 +77,7 @@ class BelongsTestCase(ForumTestCase):
self.client.login(username=u.username, password="testpass")
r = post(self.client, "forums.sticky_thread", {}, args=[f.slug, t.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_edit_thread_belongs_to_forum(self):
"""Edit thread action - thread belongs to forum."""
@ -89,7 +87,7 @@ class BelongsTestCase(ForumTestCase):
self.client.login(username=u.username, password="testpass")
r = get(self.client, "forums.edit_thread", args=[f.slug, t.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_delete_thread_belongs_to_forum(self):
"""Delete thread action - thread belongs to forum."""
@ -113,7 +111,7 @@ class BelongsTestCase(ForumTestCase):
self.client.login(username=u.username, password="testpass")
r = get(self.client, "forums.delete_thread", args=[f.slug, t.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_edit_post_belongs_to_thread_and_forum(self):
# Edit post action - post belongs to thread and thread belongs
@ -128,11 +126,11 @@ class BelongsTestCase(ForumTestCase):
# Post isn't in the passed forum:
r = get(self.client, "forums.edit_post", args=[f.slug, p.thread.id, p.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
# Post isn't in the passed thread:
r = get(self.client, "forums.edit_post", args=[p.thread.forum.slug, t.id, p.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_delete_post_belongs_to_thread_and_forum(self):
# Delete post action - post belongs to thread and thread
@ -161,8 +159,8 @@ class BelongsTestCase(ForumTestCase):
# Post isn't in the passed forum:
r = get(self.client, "forums.delete_post", args=[f.slug, p.thread.id, p.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
# Post isn't in the passed thread:
r = get(self.client, "forums.delete_post", args=[p.thread.forum.slug, t.id, p.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)

Просмотреть файл

@ -1,21 +1,20 @@
from unittest.mock import patch, Mock
from nose.tools import eq_
from unittest.mock import Mock, patch
from django.contrib.contenttypes.models import ContentType
from kitsune.access.tests import PermissionFactory
from kitsune.forums.events import NewThreadEvent, NewPostEvent
from kitsune.forums.events import NewPostEvent, NewThreadEvent
from kitsune.forums.models import Forum, Thread
from kitsune.forums.tests import (
ForumTestCase,
ForumFactory,
ForumTestCase,
PostFactory,
RestrictedForumFactory,
ThreadFactory,
PostFactory,
)
from kitsune.sumo.tests import get, post
from kitsune.sumo.urlresolvers import reverse
from kitsune.users.tests import UserFactory, GroupFactory
from kitsune.users.tests import GroupFactory, UserFactory
class PostPermissionsTests(ForumTestCase):
@ -27,7 +26,7 @@ class PostPermissionsTests(ForumTestCase):
t = ThreadFactory(forum=rforum)
response = get(self.client, "forums.posts", args=[t.forum.slug, t.id])
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
def test_reply_without_view_permission(self):
"""Posting without view_in_forum permission should 404."""
@ -39,7 +38,7 @@ class PostPermissionsTests(ForumTestCase):
response = post(
self.client, "forums.reply", {"content": "Blahs"}, args=[t.forum.slug, t.id]
)
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
def test_reply_without_post_permission(self):
"""Posting without post_in_forum permission should 403."""
@ -52,7 +51,7 @@ class PostPermissionsTests(ForumTestCase):
response = post(
self.client, "forums.reply", {"content": "Blahs"}, args=[t.forum.slug, t.id]
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_reply_thread_405(self):
"""Replying to a thread via a GET instead of a POST request."""
@ -61,7 +60,7 @@ class PostPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "forums.reply", args=[t.forum.slug, t.id])
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
class ThreadAuthorityPermissionsTests(ForumTestCase):
@ -80,7 +79,7 @@ class ThreadAuthorityPermissionsTests(ForumTestCase):
{"title": "Blahs", "content": "Blahs"},
args=[rforum.slug],
)
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
def test_new_thread_without_post_permission(self):
"""Making a new thread without post permission should 403."""
@ -95,7 +94,7 @@ class ThreadAuthorityPermissionsTests(ForumTestCase):
{"title": "Blahs", "content": "Blahs"},
args=[rforum.slug],
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_watch_GET_405(self):
"""Watch forum with HTTP GET results in 405."""
@ -104,7 +103,7 @@ class ThreadAuthorityPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "forums.watch_forum", args=[f.id])
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
def test_watch_forum_without_permission(self):
"""Watching forums without the view_in_forum permission should 404."""
@ -115,7 +114,7 @@ class ThreadAuthorityPermissionsTests(ForumTestCase):
response = self.client.post(
reverse("forums.watch_forum", args=[rforum.slug]), {"watch": "yes"}, follow=False
)
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
def test_watch_thread_without_permission(self):
"""Watching threads without the view_in_forum permission should 404."""
@ -129,13 +128,13 @@ class ThreadAuthorityPermissionsTests(ForumTestCase):
{"watch": "yes"},
follow=False,
)
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
def test_read_without_permission(self):
"""Listing threads without the view_in_forum permission should 404."""
rforum = RestrictedForumFactory()
response = get(self.client, "forums.threads", args=[rforum.slug])
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
class ThreadTests(ForumTestCase):
@ -182,7 +181,7 @@ class ThreadTests(ForumTestCase):
self.client, "forums.edit_thread", {"title": "A new title"}, args=[t.forum.slug, t.id]
)
edited_t = Thread.objects.get(id=t.id)
eq_("A new title", edited_t.title)
self.assertEqual("A new title", edited_t.title)
def test_edit_thread_moderator(self):
"""Editing post as a moderator works."""
@ -198,9 +197,9 @@ class ThreadTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
r = post(self.client, "forums.edit_thread", {"title": "new title"}, args=[f.slug, t.id])
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
edited_t = Thread.objects.get(id=t.id)
eq_("new title", edited_t.title)
self.assertEqual("new title", edited_t.title)
def test_new_thread_redirect(self):
"""Posting a new thread should redirect."""
@ -211,7 +210,7 @@ class ThreadTests(ForumTestCase):
url = reverse("forums.new_thread", args=[f.slug])
data = {"title": "some title", "content": "some content"}
r = self.client.post(url, data, follow=False)
eq_(302, r.status_code)
self.assertEqual(302, r.status_code)
assert f.slug in r["location"]
assert "last=" in r["location"]
@ -224,7 +223,7 @@ class ThreadTests(ForumTestCase):
url = reverse("forums.reply", args=[t.forum.slug, t.id])
data = {"content": "some content"}
r = self.client.post(url, data, follow=False)
eq_(302, r.status_code)
self.assertEqual(302, r.status_code)
assert t.forum.slug in r["location"]
assert str(t.id) in r["location"]
assert "last=" in r["location"]
@ -238,7 +237,7 @@ class ThreadPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "forums.edit_thread", args=[t.forum.slug, t.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_edit_locked_thread_403(self):
"""Editing a locked thread returns 403."""
@ -248,7 +247,7 @@ class ThreadPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "forums.edit_thread", args=[locked.forum.slug, locked.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_delete_thread_403(self):
"""Deleting a thread without permissions returns 403."""
@ -257,7 +256,7 @@ class ThreadPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "forums.delete_thread", args=[t.forum.slug, t.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_sticky_thread_405(self):
"""Marking a thread sticky with a HTTP GET returns 405."""
@ -266,7 +265,7 @@ class ThreadPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "forums.sticky_thread", args=[t.forum.slug, t.id])
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
def test_sticky_thread_403(self):
"""Marking a thread sticky without permissions returns 403."""
@ -275,7 +274,7 @@ class ThreadPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = post(self.client, "forums.sticky_thread", args=[t.forum.slug, t.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_locked_thread_403(self):
"""Marking a thread locked without permissions returns 403."""
@ -284,7 +283,7 @@ class ThreadPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = post(self.client, "forums.lock_thread", args=[t.forum.slug, t.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_locked_thread_405(self):
"""Marking a thread locked via a GET instead of a POST request."""
@ -293,7 +292,7 @@ class ThreadPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "forums.lock_thread", args=[t.forum.slug, t.id])
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
def test_move_thread_403(self):
"""Moving a thread without permissions returns 403."""
@ -305,7 +304,7 @@ class ThreadPermissionsTests(ForumTestCase):
response = post(
self.client, "forums.move_thread", {"forum": f.id}, args=[t.forum.slug, t.id]
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_move_thread_405(self):
"""Moving a thread via a GET instead of a POST request."""
@ -314,7 +313,7 @@ class ThreadPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "forums.move_thread", args=[t.forum.slug, t.id])
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
def test_move_thread(self):
"""Move a thread."""
@ -340,9 +339,9 @@ class ThreadPermissionsTests(ForumTestCase):
response = post(
self.client, "forums.move_thread", {"forum": f.id}, args=[t.forum.slug, t.id]
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
t = Thread.objects.get(pk=t.pk)
eq_(f.id, t.forum.id)
self.assertEqual(f.id, t.forum.id)
def test_post_edit_403(self):
"""Editing a post without permissions returns 403."""
@ -352,7 +351,7 @@ class ThreadPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "forums.edit_post", args=[t.forum.slug, t.id, p.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_post_delete_403(self):
"""Deleting a post without permissions returns 403."""
@ -362,4 +361,4 @@ class ThreadPermissionsTests(ForumTestCase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "forums.delete_post", args=[t.forum.slug, t.id, p.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)

Просмотреть файл

@ -1,11 +1,9 @@
from nose.tools import eq_
from kitsune.sumo.urlresolvers import reverse
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
class TestImageListView(TestCase):
def test_it_works(self):
url = reverse("image-list")
res = self.client.get(url)
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)

Просмотреть файл

@ -1,8 +1,7 @@
from django.core.files.base import ContentFile
from nose.tools import eq_
from unittest.mock import patch
from django.core.files.base import ContentFile
from kitsune.gallery.models import Image
from kitsune.gallery.tests import ImageFactory
from kitsune.sumo.tests import TestCase
@ -19,8 +18,8 @@ class ImageTestCase(TestCase):
"""thumbnail_url_if_set() returns self.thumbnail if set, or else
returns self.file"""
img = ImageFactory()
eq_(img.file.url, img.thumbnail_url_if_set())
self.assertEqual(img.file.url, img.thumbnail_url_if_set())
create_thumbnail_mock.return_value = ContentFile("the dude")
generate_thumbnail(img, "file", "thumbnail")
eq_(img.thumbnail.url, img.thumbnail_url_if_set())
self.assertEqual(img.thumbnail.url, img.thumbnail_url_if_set())

Просмотреть файл

@ -1,10 +1,9 @@
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.gallery.models import Image, Video
from kitsune.gallery.tests import ImageFactory, VideoFactory
from kitsune.sumo.templatetags.jinja_helpers import urlparams
from kitsune.sumo.tests import TestCase, get, LocalizingClient, post
from kitsune.sumo.tests import LocalizingClient, TestCase, get, post
from kitsune.sumo.urlresolvers import reverse
from kitsune.users.tests import UserFactory
@ -22,28 +21,28 @@ class GalleryPageCase(TestCase):
"""
img = ImageFactory()
response = get(self.client, "gallery.gallery", args=["image"])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
imgs = doc("#media-list li img")
eq_(1, len(imgs))
eq_(img.thumbnail_url_if_set(), imgs[0].attrib["src"])
self.assertEqual(1, len(imgs))
self.assertEqual(img.thumbnail_url_if_set(), imgs[0].attrib["src"])
def test_gallery_locale(self):
"""Test that images only show for their set locale."""
ImageFactory(locale="es")
url = reverse("gallery.gallery", args=["image"])
response = self.client.get(url, follow=True)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
imgs = doc("#media-list li img")
eq_(0, len(imgs))
self.assertEqual(0, len(imgs))
locale_url = reverse("gallery.gallery", locale="es", args=["image"])
response = self.client.get(locale_url, follow=True)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
imgs = doc("#media-list li img")
eq_(1, len(imgs))
self.assertEqual(1, len(imgs))
class GalleryAsyncCase(TestCase):
@ -56,29 +55,29 @@ class GalleryAsyncCase(TestCase):
img = ImageFactory()
url = urlparams(reverse("gallery.async"), type="image")
response = self.client.get(url, follow=True)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
imgs = doc("#media-list li img")
eq_(1, len(imgs))
eq_(img.thumbnail_url_if_set(), imgs[0].attrib["src"])
self.assertEqual(1, len(imgs))
self.assertEqual(img.thumbnail_url_if_set(), imgs[0].attrib["src"])
def test_gallery_image_search(self):
"""Test for ajax endpoint with search parameter."""
img = ImageFactory()
url = urlparams(reverse("gallery.async"), type="image", q="foobar")
response = self.client.get(url, follow=True)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
imgs = doc("#media-list li img")
eq_(0, len(imgs))
self.assertEqual(0, len(imgs))
url = urlparams(reverse("gallery.async"), type="image", q=img.title)
response = self.client.get(url, follow=True)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
imgs = doc("#media-list li img")
eq_(1, len(imgs))
eq_(img.thumbnail_url_if_set(), imgs[0].attrib["src"])
self.assertEqual(1, len(imgs))
self.assertEqual(img.thumbnail_url_if_set(), imgs[0].attrib["src"])
class GalleryUploadTestCase(TestCase):
@ -99,10 +98,10 @@ class GalleryUploadTestCase(TestCase):
"""The image draft is loaded for this user."""
img = ImageFactory(is_draft=True, creator=self.u)
response = get(self.client, "gallery.gallery", args=["image"])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
assert doc(".file.preview img").attr("src").endswith(img.file.name)
eq_(1, doc(".file.preview img").length)
self.assertEqual(1, doc(".file.preview img").length)
def test_image_draft_post(self):
"""Posting to the page saves the field values for the image draft."""
@ -113,26 +112,26 @@ class GalleryUploadTestCase(TestCase):
{"description": "??", "title": "test"},
args=["image"],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
# Preview for all 3 video formats: flv, ogv, webm
eq_("??", doc("#gallery-upload-modal textarea").html().strip())
eq_("test", doc('#gallery-upload-modal input[name="title"]').val())
self.assertEqual("??", doc("#gallery-upload-modal textarea").html().strip())
self.assertEqual("test", doc('#gallery-upload-modal input[name="title"]').val())
def test_video_draft_post(self):
"""Posting to the page saves the field values for the video draft."""
VideoFactory(is_draft=True, creator=self.u)
response = post(self.client, "gallery.gallery", {"title": "zTestz"}, args=["image"])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
# Preview for all 3 video formats: flv, ogv, webm
eq_("zTestz", doc('#gallery-upload-modal input[name="title"]').val())
self.assertEqual("zTestz", doc('#gallery-upload-modal input[name="title"]').val())
def test_modal_locale_selected(self):
"""Locale value is selected for upload modal."""
response = get(self.client, "gallery.gallery", args=["image"], locale="fr")
doc = pq(response.content)
eq_("fr", doc('#gallery-upload-image option[selected="selected"]').val())
self.assertEqual("fr", doc('#gallery-upload-image option[selected="selected"]').val())
class MediaPageCase(TestCase):
@ -144,8 +143,8 @@ class MediaPageCase(TestCase):
"""Test the media page."""
img = ImageFactory()
response = self.client.get(img.get_absolute_url(), follow=True)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(img.title, doc("h1").text())
eq_(img.description, doc("#media-object div.description").text())
eq_(img.file.url, doc("#media-view img")[0].attrib["src"])
self.assertEqual(img.title, doc("h1").text())
self.assertEqual(img.description, doc("#media-object div.description").text())
self.assertEqual(img.file.url, doc("#media-view img")[0].attrib["src"])

Просмотреть файл

@ -1,8 +1,6 @@
from django.core.exceptions import PermissionDenied
from django.core.files import File
from nose.tools import raises
from kitsune.gallery.models import Image, Video
from kitsune.gallery.tests import ImageFactory, VideoFactory
from kitsune.gallery.utils import check_media_permissions, create_image
@ -27,12 +25,12 @@ class CheckPermissionsTestCase(TestCase):
vid = VideoFactory(creator=self.user)
check_media_permissions(vid, self.user, "change")
@raises(PermissionDenied)
def test_check_not_own_object(self):
"""tagger cannot delete an image s/he doesn't own."""
img = ImageFactory()
# This should raise
check_media_permissions(img, self.user, "delete")
with self.assertRaises(PermissionDenied):
check_media_permissions(img, self.user, "delete")
def test_check_has_perm(self):
"""User with django permission has perm to change video."""

Просмотреть файл

@ -1,16 +1,15 @@
from unittest import mock
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.gallery import views
from kitsune.gallery.models import Image, Video
from kitsune.gallery.tests import ImageFactory, VideoFactory
from kitsune.gallery.views import _get_media_info
from kitsune.sumo.tests import post, LocalizingClient, TestCase
from kitsune.sumo.tests import LocalizingClient, TestCase, post
from kitsune.sumo.urlresolvers import reverse
from kitsune.users.tests import UserFactory, add_permission
TEST_IMG = "kitsune/upload/tests/media/test.jpg"
@ -32,8 +31,8 @@ class DeleteEditImageTests(TestCase):
self.client.login(username=u.username, password="testpass")
r = post(self.client, "gallery.delete_media", args=["image", im.id])
eq_(200, r.status_code)
eq_(0, Image.objects.count())
self.assertEqual(200, r.status_code)
self.assertEqual(0, Image.objects.count())
def test_delete_image_without_permissions(self):
"""Can't delete an image I didn't create."""
@ -42,8 +41,8 @@ class DeleteEditImageTests(TestCase):
self.client.login(username=u.username, password="testpass")
r = post(self.client, "gallery.delete_media", args=["image", img.id])
eq_(403, r.status_code)
eq_(1, Image.objects.count())
self.assertEqual(403, r.status_code)
self.assertEqual(1, Image.objects.count())
def test_delete_own_image(self):
"""Can delete an image I created."""
@ -52,8 +51,8 @@ class DeleteEditImageTests(TestCase):
img = ImageFactory(creator=u)
r = post(self.client, "gallery.delete_media", args=["image", img.id])
eq_(200, r.status_code)
eq_(0, Image.objects.count())
self.assertEqual(200, r.status_code)
self.assertEqual(0, Image.objects.count())
@mock.patch.object(views, "schedule_rebuild_kb")
def test_schedule_rebuild_kb_on_delete(self, schedule_rebuild_kb):
@ -64,8 +63,8 @@ class DeleteEditImageTests(TestCase):
self.client.login(username=u.username, password="testpass")
r = post(self.client, "gallery.delete_media", args=["image", im.id])
eq_(200, r.status_code)
eq_(0, Image.objects.count())
self.assertEqual(200, r.status_code)
self.assertEqual(0, Image.objects.count())
assert schedule_rebuild_kb.called
def test_edit_own_image(self):
@ -77,8 +76,8 @@ class DeleteEditImageTests(TestCase):
self.client, "gallery.edit_media", {"description": "arrr"}, args=["image", img.id]
)
eq_(200, r.status_code)
eq_("arrr", Image.objects.get().description)
self.assertEqual(200, r.status_code)
self.assertEqual("arrr", Image.objects.get().description)
def test_edit_image_without_permissions(self):
"""Can't edit an image I didn't create."""
@ -89,7 +88,7 @@ class DeleteEditImageTests(TestCase):
self.client, "gallery.edit_media", {"description": "arrr"}, args=["image", img.id]
)
eq_(403, r.status_code)
self.assertEqual(403, r.status_code)
def test_edit_image_with_permissions(self):
"""Editing image sets the updated_by field."""
@ -101,8 +100,8 @@ class DeleteEditImageTests(TestCase):
self.client, "gallery.edit_media", {"description": "arrr"}, args=["image", img.id]
)
eq_(200, r.status_code)
eq_(u.username, Image.objects.get().updated_by.username)
self.assertEqual(200, r.status_code)
self.assertEqual(u.username, Image.objects.get().updated_by.username)
class ViewHelpersTests(TestCase):
@ -115,15 +114,15 @@ class ViewHelpersTests(TestCase):
"""Gets video and format info."""
vid = VideoFactory()
info_vid, info_format = _get_media_info(vid.pk, "video")
eq_(vid.pk, info_vid.pk)
eq_(None, info_format)
self.assertEqual(vid.pk, info_vid.pk)
self.assertEqual(None, info_format)
def test_get_media_info_image(self):
"""Gets image and format info."""
img = ImageFactory()
info_img, info_format = _get_media_info(img.pk, "image")
eq_(img.pk, info_img.pk)
eq_("jpeg", info_format)
self.assertEqual(img.pk, info_img.pk)
self.assertEqual("jpeg", info_format)
class SearchTests(TestCase):
@ -135,7 +134,7 @@ class SearchTests(TestCase):
url = reverse("gallery.search", args=["image"])
response = self.client.get(url, {"q": "quicktime"}, follow=True)
doc = pq(response.content)
eq_(1, len(doc("#media-list li")))
self.assertEqual(1, len(doc("#media-list li")))
def test_video_search(self):
VideoFactory(title="0a85171f1802a3b0d9f46ffb997ddc02-1251659983-259-2.mp4")
@ -143,7 +142,7 @@ class SearchTests(TestCase):
url = reverse("gallery.search", args=["video"])
response = self.client.get(url, {"q": "1802"}, follow=True)
doc = pq(response.content)
eq_(1, len(doc("#media-list li")))
self.assertEqual(1, len(doc("#media-list li")))
def test_search_description(self):
ImageFactory(description="This image was automatically migrated")
@ -152,22 +151,22 @@ class SearchTests(TestCase):
url = reverse("gallery.search", args=["image"])
response = self.client.get(url, {"q": "migrated"}, follow=True)
doc = pq(response.content)
eq_(2, len(doc("#media-list li")))
self.assertEqual(2, len(doc("#media-list li")))
def test_search_nonexistent(self):
url = reverse("gallery.search", args=["foo"])
response = self.client.get(url, {"q": "foo"}, follow=True)
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
class GalleryTests(TestCase):
def test_gallery_invalid_type(self):
url = reverse("gallery.gallery", args=["foo"])
response = self.client.get(url, follow=True)
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
def test_redirect(self):
"""/gallery redirects to /gallery/images"""
response = self.client.get(reverse("gallery.home", locale="en-US"), follow=False)
eq_(301, response.status_code)
eq_("/en-US/gallery/images", response["location"])
self.assertEqual(301, response.status_code)
self.assertEqual("/en-US/gallery/images", response["location"])

Просмотреть файл

@ -1,12 +1,11 @@
import re
from django.conf import settings
from unittest.mock import Mock
from nose.tools import eq_
from django.conf import settings
from pyquery import PyQuery as pq
from kitsune.groups.templatetags.jinja_helpers import group_avatar, group_link
from kitsune.groups.models import GroupProfile
from kitsune.groups.templatetags.jinja_helpers import group_avatar, group_link
from kitsune.groups.tests import GroupProfileFactory
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
@ -17,7 +16,7 @@ class GroupHelperTests(TestCase):
def test_group_link_no_profile(self):
g = GroupFactory()
text = group_link(g)
eq_(g.name, text)
self.assertEqual(g.name, text)
def test_group_link_with_profile(self):
g = GroupFactory()
@ -25,21 +24,21 @@ class GroupHelperTests(TestCase):
p = GroupProfile.objects.create(group=g, slug="foo")
text = group_link(g)
doc = pq(text)
eq_(reverse("groups.profile", args=[p.slug]), doc("a")[0].attrib["href"])
eq_(g.name, doc("a")[0].text)
self.assertEqual(reverse("groups.profile", args=[p.slug]), doc("a")[0].attrib["href"])
self.assertEqual(g.name, doc("a")[0].text)
def test_right_group_profile(self):
"""Make sure we get the right group profile."""
g1 = GroupFactory(pk=100)
g1.save()
eq_(100, g1.pk)
self.assertEqual(100, g1.pk)
g2 = GroupFactory(pk=101)
g2.save()
eq_(101, g2.pk)
self.assertEqual(101, g2.pk)
p = GroupProfileFactory(pk=100, group=g2, slug="foo")
eq_(100, p.pk)
self.assertEqual(100, p.pk)
eq_(group_link(g1), g1.name)
self.assertEqual(group_link(g1), g1.name)
def test_group_avatar(self):
g = GroupFactory()
@ -50,4 +49,4 @@ class GroupHelperTests(TestCase):
p.avatar = Mock()
p.avatar.url = "/foo/bar"
url = group_avatar(p)
eq_("/foo/bar", url)
self.assertEqual("/foo/bar", url)

Просмотреть файл

@ -2,14 +2,12 @@ import os
from django.core.files import File
from nose.tools import eq_
from kitsune.groups.models import GroupProfile
from kitsune.groups.tests import GroupProfileFactory
from kitsune.sumo.templatetags.jinja_helpers import urlparams
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
from kitsune.users.tests import UserFactory, GroupFactory, add_permission
from kitsune.users.tests import GroupFactory, UserFactory, add_permission
class EditGroupProfileTests(TestCase):
@ -23,14 +21,14 @@ class EditGroupProfileTests(TestCase):
slug = self.group_profile.slug
# Verify GET
r = self.client.get(reverse("groups.edit", args=[slug]), follow=True)
eq_(r.status_code, 200)
self.assertEqual(r.status_code, 200)
# Verify POST
r = self.client.post(
reverse("groups.edit", locale="en-US", args=[slug]), {"information": "=new info="}
)
eq_(r.status_code, 302)
self.assertEqual(r.status_code, 302)
gp = GroupProfile.objects.get(slug=slug)
eq_(gp.information, "=new info=")
self.assertEqual(gp.information, "=new info=")
def test_edit_with_perm(self):
add_permission(self.user, GroupProfile, "change_groupprofile")
@ -44,12 +42,12 @@ class EditGroupProfileTests(TestCase):
slug = self.group_profile.slug
# Try GET
r = self.client.get(reverse("groups.edit", args=[slug]), follow=True)
eq_(r.status_code, 403)
self.assertEqual(r.status_code, 403)
# Try POST
r = self.client.post(
reverse("groups.edit", locale="en-US", args=[slug]), {"information": "=new info="}
)
eq_(r.status_code, 403)
self.assertEqual(r.status_code, 403)
class EditAvatarTests(TestCase):
@ -77,9 +75,9 @@ class EditAvatarTests(TestCase):
with open("kitsune/upload/tests/media/test.jpg", "rb") as f:
r = self.client.post(url, {"avatar": f})
eq_(302, r.status_code)
self.assertEqual(302, r.status_code)
url = reverse("groups.profile", args=[self.group_profile.slug])
eq_("/en-US" + url, r["location"])
self.assertEqual("/en-US" + url, r["location"])
assert not os.path.exists(old_path), "Old avatar was not removed."
def test_delete_avatar(self):
@ -88,13 +86,13 @@ class EditAvatarTests(TestCase):
url = reverse("groups.delete_avatar", locale="en-US", args=[self.group_profile.slug])
r = self.client.get(url)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
r = self.client.post(url)
eq_(302, r.status_code)
self.assertEqual(302, r.status_code)
url = reverse("groups.profile", args=[self.group_profile.slug])
eq_("/en-US" + url, r["location"])
self.assertEqual("/en-US" + url, r["location"])
gp = GroupProfile.objects.get(slug=self.group_profile.slug)
eq_("", gp.avatar.name)
self.assertEqual("", gp.avatar.name)
class AddRemoveMemberTests(TestCase):
@ -109,9 +107,9 @@ class AddRemoveMemberTests(TestCase):
def test_add_member(self):
url = reverse("groups.add_member", locale="en-US", args=[self.group_profile.slug])
r = self.client.get(url)
eq_(405, r.status_code)
self.assertEqual(405, r.status_code)
r = self.client.post(url, {"users": self.member.username})
eq_(302, r.status_code)
self.assertEqual(302, r.status_code)
assert self.member in self.group_profile.group.user_set.all()
def test_remove_member(self):
@ -120,9 +118,9 @@ class AddRemoveMemberTests(TestCase):
"groups.remove_member", locale="en-US", args=[self.group_profile.slug, self.member.id]
)
r = self.client.get(url)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
r = self.client.post(url)
eq_(302, r.status_code)
self.assertEqual(302, r.status_code)
assert self.member not in self.group_profile.group.user_set.all()
@ -138,9 +136,9 @@ class AddRemoveLeaderTests(TestCase):
def test_add_leader(self):
url = reverse("groups.add_leader", locale="en-US", args=[self.group_profile.slug])
r = self.client.get(url)
eq_(405, r.status_code)
self.assertEqual(405, r.status_code)
r = self.client.post(url, {"users": self.leader.username})
eq_(302, r.status_code)
self.assertEqual(302, r.status_code)
assert self.leader in self.group_profile.leaders.all()
def test_remove_member(self):
@ -149,9 +147,9 @@ class AddRemoveLeaderTests(TestCase):
"groups.remove_leader", locale="en-US", args=[self.group_profile.slug, self.leader.id]
)
r = self.client.get(url)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
r = self.client.post(url)
eq_(302, r.status_code)
self.assertEqual(302, r.status_code)
assert self.leader not in self.group_profile.leaders.all()
@ -167,8 +165,8 @@ class JoinContributorsTests(TestCase):
url = reverse("groups.join_contributors", locale="en-US")
url = urlparams(url, next=next)
r = self.client.get(url)
eq_(405, r.status_code)
self.assertEqual(405, r.status_code)
r = self.client.post(url)
eq_(302, r.status_code)
eq_(next, r["location"])
self.assertEqual(302, r.status_code)
self.assertEqual(next, r["location"])
assert self.user.groups.filter(name="Contributors").exists()

Просмотреть файл

@ -1,10 +1,8 @@
from unittest import mock
from urllib.parse import urlparse
from django.contrib.sites.models import Site
from unittest import mock
import waffle
from nose.tools import eq_
from django.contrib.sites.models import Site
from kitsune.inproduct.tests import RedirectFactory
from kitsune.sumo.tests import TestCase
@ -73,7 +71,7 @@ class RedirectTestCase(TestCase):
for input, output in urls:
response = self.client.get("/1/%s" % input, follow=True)
if output == 404:
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
elif output.startswith("http"):
chain = [u[0] for u in response.redirect_chain]
assert output in chain
@ -81,8 +79,8 @@ class RedirectTestCase(TestCase):
r = response.redirect_chain
r.reverse()
final = urlparse(r[0][0])
eq_(output, final.path)
eq_(querystring, final.query)
self.assertEqual(output, final.path)
self.assertEqual(querystring, final.query)
@mock.patch.object(Site.objects, "get_current")
@mock.patch.object(waffle, "sample_is_active")
@ -92,5 +90,5 @@ class RedirectTestCase(TestCase):
sample_is_active.return_value = True
response = self.client.get("/1/firefox/4.0/Linux/en-US/prefs-applications")
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
assert response["location"].startswith("https://example.com/")

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.karma.models import Title
from kitsune.users.tests import TestCase, UserFactory
@ -14,13 +12,13 @@ class KarmaTitleTests(TestCase):
Title.objects.set_top10_contributors([u1.id, u2.id, u3.id])
top10_title = Title.objects.get(name=title)
assert top10_title.is_auto
eq_(3, len(top10_title.users.all()))
self.assertEqual(3, len(top10_title.users.all()))
# Update title to different list of users
u4 = UserFactory()
Title.objects.set_top10_contributors([u1.id, u3.id, u4.id])
top10_title = Title.objects.get(name=title)
assert top10_title.is_auto
eq_(3, len(top10_title.users.all()))
self.assertEqual(3, len(top10_title.users.all()))
assert u4 in top10_title.users.all()
assert u2 not in top10_title.users.all()

Просмотреть файл

@ -1,8 +1,6 @@
from nose.tools import eq_
from kitsune.karma.templatetags.jinja_helpers import karma_titles
from kitsune.karma.models import Title
from kitsune.users.tests import TestCase, UserFactory, GroupFactory
from kitsune.karma.templatetags.jinja_helpers import karma_titles
from kitsune.users.tests import GroupFactory, TestCase, UserFactory
class KarmaTitleHelperTests(TestCase):
@ -18,8 +16,8 @@ class KarmaTitleHelperTests(TestCase):
t.save()
t.users.add(self.user)
titles = karma_titles(self.user)
eq_(1, len(titles))
eq_(title, titles[0].name)
self.assertEqual(1, len(titles))
self.assertEqual(title, titles[0].name)
def test_group_title(self):
title = "Group Title"
@ -27,8 +25,8 @@ class KarmaTitleHelperTests(TestCase):
t.save()
t.groups.add(self.group)
titles = karma_titles(self.user)
eq_(1, len(titles))
eq_(title, titles[0].name)
self.assertEqual(1, len(titles))
self.assertEqual(title, titles[0].name)
def test_user_and_group_title(self):
u_title = "User Title"
@ -40,6 +38,6 @@ class KarmaTitleHelperTests(TestCase):
t.save()
t.groups.add(self.group)
titles = [k.name for k in karma_titles(self.user)]
eq_(2, len(titles))
self.assertEqual(2, len(titles))
assert u_title in titles
assert g_title in titles

Просмотреть файл

@ -1,7 +1,5 @@
from django.core import mail
from nose.tools import eq_
from kitsune.kbadge.tests import AwardFactory, BadgeFactory
from kitsune.sumo.tests import TestCase
@ -17,12 +15,12 @@ class AwardNotificationTests(TestCase):
new_badge = BadgeFactory()
# Check the mail queue first.
eq_(0, len(mail.outbox))
self.assertEqual(0, len(mail.outbox))
# Create an award and save it. This triggers the notification.
AwardFactory(description="yay!", badge=new_badge)
eq_(1, len(mail.outbox))
self.assertEqual(1, len(mail.outbox))
# TODO: test contents--not doing that now because it's a
# mockup.

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.kbadge.tests import AwardFactory, BadgeFactory
from kitsune.sumo.tests import LocalizingClient, TestCase
from kitsune.sumo.urlresolvers import reverse
@ -10,7 +8,7 @@ class AwardsListTests(TestCase):
def test_list_empty(self):
resp = self.client.get(reverse("kbadge.awards_list"), follow=True)
eq_(200, resp.status_code)
self.assertEqual(200, resp.status_code)
def test_list_with_awards(self):
b = BadgeFactory()
@ -19,7 +17,7 @@ class AwardsListTests(TestCase):
a3 = AwardFactory(description="A3 AWARD", badge=b)
resp = self.client.get(reverse("kbadge.awards_list"), follow=True)
eq_(200, resp.status_code)
self.assertEqual(200, resp.status_code)
self.assertContains(resp, a1.user.username)
self.assertContains(resp, a1.get_absolute_url())
self.assertContains(resp, a2.user.username)
@ -34,4 +32,4 @@ class AwardDetailsTests(TestCase):
a1 = AwardFactory(description="A1 AWARD")
resp = self.client.get(a1.get_absolute_url(), follow=True)
eq_(200, resp.status_code)
self.assertEqual(200, resp.status_code)

Просмотреть файл

@ -1,11 +1,9 @@
import factory
from django.conf import settings
import factory
from nose.tools import eq_
from kitsune.kbforums.models import Thread, Post, ThreadLockedError
from kitsune.kbforums.models import Post, Thread, ThreadLockedError
from kitsune.kbforums.views import sort_threads
from kitsune.sumo.tests import get, LocalizingClient, TestCase
from kitsune.sumo.tests import LocalizingClient, TestCase, get
from kitsune.users.tests import UserFactory
from kitsune.wiki.tests import DocumentFactory
@ -36,7 +34,7 @@ class PostTestCase(KBForumTestCase):
that thread to point to the new post."""
t = ThreadFactory()
post = t.new_post(creator=t.creator, content="an update")
eq_(post.id, t.last_post_id)
self.assertEqual(post.id, t.last_post_id)
def test_update_post_does_not_update_thread(self):
"""Updating/saving an old post in a thread should _not_ update the
@ -44,7 +42,7 @@ class PostTestCase(KBForumTestCase):
p = PostFactory()
old = p.thread.last_post_id
p.content = "updated content"
eq_(old, p.thread.last_post_id)
self.assertEqual(old, p.thread.last_post_id)
def test_replies_count(self):
"""The Thread.replies value should remain one less than the number of
@ -52,14 +50,14 @@ class PostTestCase(KBForumTestCase):
t = ThreadFactory()
old = t.replies
t.new_post(creator=t.creator, content="test")
eq_(old, t.replies)
self.assertEqual(old, t.replies)
def test_sticky_threads_first(self):
"""Sticky threads should come before non-sticky threads."""
ThreadFactory()
t2 = ThreadFactory(is_sticky=True)
s = Thread.objects.all()[0]
eq_(t2.id, s.id)
self.assertEqual(t2.id, s.id)
def test_thread_sorting(self):
"""After the sticky threads, threads should be sorted by the created
@ -98,10 +96,10 @@ class PostTestCase(KBForumTestCase):
t2.new_post(t2.creator, "baz")
threads = sort_threads(Thread.objects, 4)
self.assertLessEqual(threads[0].replies, threads[1].replies)
eq_(threads[0].replies, t1.replies)
eq_(threads[1].replies, t2.replies)
eq_(threads[0].title, t1.title)
eq_(threads[1].title, t2.title)
self.assertEqual(threads[0].replies, t1.replies)
self.assertEqual(threads[1].replies, t2.replies)
self.assertEqual(threads[0].title, t1.title)
self.assertEqual(threads[1].title, t2.title)
def test_sorting_last_post_desc(self):
"""Sorting threads by last_post descendingly."""
@ -125,7 +123,7 @@ class PostTestCase(KBForumTestCase):
)
for replies, pages in test_data:
t.replies = replies
eq_(t.last_page, pages)
self.assertEqual(t.last_page, pages)
def test_locked_thread(self):
"""Trying to reply to a locked thread should raise an exception."""
@ -136,7 +134,7 @@ class PostTestCase(KBForumTestCase):
def test_post_no_session(self):
r = get(self.client, "wiki.discuss.new_thread", kwargs={"document_slug": "article-title"})
assert settings.LOGIN_URL in r.redirect_chain[0][0]
eq_(302, r.redirect_chain[0][1])
self.assertEqual(302, r.redirect_chain[0][1])
class ThreadTestCase(KBForumTestCase):
@ -148,4 +146,4 @@ class ThreadTestCase(KBForumTestCase):
kwargs={"document_slug": "article-title", "thread_id": 1},
)
assert settings.LOGIN_URL in r.redirect_chain[0][0]
eq_(302, r.redirect_chain[0][1])
self.assertEqual(302, r.redirect_chain[0][1])

Просмотреть файл

@ -1,10 +1,9 @@
import time
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.kbforums.feeds import ThreadsFeed, PostsFeed
from kitsune.kbforums.tests import KBForumTestCase, get, ThreadFactory
from kitsune.kbforums.feeds import PostsFeed, ThreadsFeed
from kitsune.kbforums.tests import KBForumTestCase, ThreadFactory, get
from kitsune.wiki.tests import DocumentFactory
@ -18,7 +17,7 @@ class FeedSortingTestCase(KBForumTestCase):
t2 = ThreadFactory(document=d)
t2.new_post(creator=t2.creator, content="foo")
given_ = ThreadsFeed().items(d)[0].id
eq_(t2.id, given_)
self.assertEqual(t2.id, given_)
def test_posts_sort(self):
"""Ensure that posts are being sorted properly by date/time."""
@ -27,7 +26,7 @@ class FeedSortingTestCase(KBForumTestCase):
time.sleep(1)
p2 = t.new_post(creator=t.creator, content="foo")
given_ = PostsFeed().items(t)[0].id
eq_(p2.id, given_)
self.assertEqual(p2.id, given_)
def test_multi_feed_titling(self):
"""Ensure that titles are being applied properly to feeds."""
@ -36,4 +35,4 @@ class FeedSortingTestCase(KBForumTestCase):
doc = pq(response.content)
given_ = doc('link[type="application/atom+xml"]')[0].attrib["title"]
exp_ = ThreadsFeed().title(d)
eq_(exp_, given_)
self.assertEqual(exp_, given_)

Просмотреть файл

@ -1,11 +1,9 @@
import datetime
from nose.tools import eq_
from kitsune.kbforums.models import Thread
from kitsune.kbforums.tests import KBForumTestCase, ThreadFactory, PostFactory
from kitsune.sumo.urlresolvers import reverse
from kitsune.kbforums.tests import KBForumTestCase, PostFactory, ThreadFactory
from kitsune.sumo.templatetags.jinja_helpers import urlparams
from kitsune.sumo.urlresolvers import reverse
from kitsune.users.tests import UserFactory
from kitsune.wiki.tests import DocumentFactory
@ -16,7 +14,7 @@ class KBForumModelTestCase(KBForumTestCase):
exp_ = reverse(
"wiki.discuss.posts", locale=t.document.locale, args=[t.document.slug, t.id]
)
eq_(exp_, t.get_absolute_url())
self.assertEqual(exp_, t.get_absolute_url())
def test_post_absolute_url(self):
t = ThreadFactory()
@ -27,7 +25,7 @@ class KBForumModelTestCase(KBForumTestCase):
args=[p.thread.document.slug, p.thread.id],
)
exp_ = urlparams(url_, hash="post-%s" % p.id)
eq_(exp_, p.get_absolute_url())
self.assertEqual(exp_, p.get_absolute_url())
def test_last_post_updated(self):
"""Adding/Deleting the last post in a thread should
@ -38,7 +36,7 @@ class KBForumModelTestCase(KBForumTestCase):
# add a new post, then check that last_post is updated
new_post = t.new_post(creator=u, content="test")
eq_(t.last_post.id, new_post.id)
self.assertEqual(t.last_post.id, new_post.id)
# delete the new post, then check that last_post is updated
new_post.delete()
@ -50,9 +48,9 @@ class KBThreadModelTestCase(KBForumTestCase):
"""Deleting the only post in a thread should delete the thread"""
t = ThreadFactory(title="test")
p = t.new_post(creator=t.creator, content="test")
eq_(1, t.post_set.count())
self.assertEqual(1, t.post_set.count())
p.delete()
eq_(0, Thread.objects.filter(pk=t.id).count())
self.assertEqual(0, Thread.objects.filter(pk=t.id).count())
class KBSaveDateTestCase(KBForumTestCase):
@ -92,14 +90,14 @@ class KBSaveDateTestCase(KBForumTestCase):
created = datetime.datetime(1992, 1, 12, 9, 48, 23)
t = self.doc.thread_set.create(title="foo", creator=self.user, created=created)
t.save()
eq_(created, t.created)
self.assertEqual(created, t.created)
def test_save_old_thread_created(self):
"""Saving an old thread should not change its created date."""
t = ThreadFactory()
created = t.created
t.save()
eq_(created, t.created)
self.assertEqual(created, t.created)
def test_save_new_post_no_timestamps(self):
"""
@ -141,4 +139,4 @@ class KBSaveDateTestCase(KBForumTestCase):
def test_content_parsed_sanity(self):
"""The content_parsed field is populated."""
p = PostFactory(content="yet another post")
eq_("<p>yet another post\n</p>", p.content_parsed)
self.assertEqual("<p>yet another post\n</p>", p.content_parsed)

Просмотреть файл

@ -1,19 +1,17 @@
from unittest import mock
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core import mail
from unittest import mock
from nose.tools import eq_
from kitsune.kbforums.events import NewPostEvent, NewThreadEvent
from kitsune.kbforums.models import Thread, Post
from kitsune.kbforums.models import Post, Thread
from kitsune.kbforums.tests import KBForumTestCase, ThreadFactory
from kitsune.sumo.tests import post, attrs_eq, starts_with
from kitsune.sumo.tests import attrs_eq, post, starts_with
from kitsune.users.models import Setting
from kitsune.users.tests import UserFactory
from kitsune.wiki.tests import DocumentFactory
# Some of these contain a locale prefix on included links, while others don't.
# This depends on whether the tests use them inside or outside the scope of a
# request. See the long explanation in questions.tests.test_notifications.
@ -277,7 +275,7 @@ class NotificationsTests(KBForumTestCase):
self.client.login(username=u2.username, password="testpass")
post(self.client, "wiki.discuss.reply", {"content": "a post"}, args=[f.slug, t.id])
eq_(1, len(mail.outbox))
self.assertEqual(1, len(mail.outbox))
p = Post.objects.all().order_by("-id")[0]
attrs_eq(mail.outbox[0], to=[u.email], subject="Re: an article title - Sticky Thread")
starts_with(
@ -311,7 +309,7 @@ class NotificationsTests(KBForumTestCase):
post(self.client, "wiki.discuss.reply", {"content": "a post"}, args=[d.slug, t.id])
# Email was sent as expected.
eq_(1, len(mail.outbox))
self.assertEqual(1, len(mail.outbox))
p = Post.objects.all().order_by("-id")[0]
attrs_eq(mail.outbox[0], to=[u.email], subject="Re: an article title - Sticky Thread")
starts_with(
@ -344,7 +342,7 @@ class NotificationsTests(KBForumTestCase):
post(self.client, "wiki.discuss.reply", {"content": "a post"}, args=[d.slug, t.id])
# Only ONE email was sent. As expected.
eq_(1, len(mail.outbox))
self.assertEqual(1, len(mail.outbox))
p = Post.objects.all().order_by("-id")[0]
attrs_eq(mail.outbox[0], to=[u.email], subject="Re: an article title - Sticky Thread")
starts_with(
@ -379,7 +377,7 @@ class NotificationsTests(KBForumTestCase):
)
# Email was not sent.
eq_(0, len(mail.outbox))
self.assertEqual(0, len(mail.outbox))
@mock.patch.object(Site.objects, "get_current")
def test_watch_locale_then_new_thread(self, get_current):

Просмотреть файл

@ -1,15 +1,14 @@
import time
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.flagit.models import FlaggedObject
from kitsune.kbforums.models import Post, Thread
from kitsune.kbforums.tests import KBForumTestCase, ThreadFactory, PostFactory
from kitsune.sumo.urlresolvers import reverse
from kitsune.kbforums.tests import KBForumTestCase, PostFactory, ThreadFactory
from kitsune.sumo.tests import get, post
from kitsune.sumo.urlresolvers import reverse
from kitsune.users.tests import UserFactory, add_permission
from kitsune.wiki.tests import DocumentFactory, ApprovedRevisionFactory
from kitsune.wiki.tests import ApprovedRevisionFactory, DocumentFactory
class PostsTemplateTests(KBForumTestCase):
@ -24,7 +23,7 @@ class PostsTemplateTests(KBForumTestCase):
doc = pq(response.content)
error_msg = doc("ul.errorlist li a")[0]
eq_(error_msg.text, "Please provide a message.")
self.assertEqual(error_msg.text, "Please provide a message.")
def test_edit_post_errors(self):
"""Changing post content works."""
@ -42,7 +41,7 @@ class PostsTemplateTests(KBForumTestCase):
doc = pq(response.content)
errors = doc("ul.errorlist li a")
eq_(
self.assertEqual(
errors[0].text,
"Your message is too short (4 characters). It must be at least 5 characters.",
)
@ -61,7 +60,7 @@ class PostsTemplateTests(KBForumTestCase):
)
doc = pq(res.content)
eq_(len(doc("form.edit-post")), 1)
self.assertEqual(len(doc("form.edit-post")), 1)
def test_edit_post(self):
"""Changing post content works."""
@ -79,7 +78,7 @@ class PostsTemplateTests(KBForumTestCase):
)
edited_p = t.post_set.get(pk=p.id)
eq_("Some new content", edited_p.content)
self.assertEqual("Some new content", edited_p.content)
# TODO: This test should be enabled once the responsive redesign milestone is complete.
# def test_long_title_truncated_in_crumbs(self):
@ -89,7 +88,7 @@ class PostsTemplateTests(KBForumTestCase):
# response = get(self.client, 'wiki.discuss.posts', args=[d.slug, t.id])
# doc = pq(response.content)
# crumb = doc('#breadcrumbs li:last-child')
# eq_(crumb.text(), 'A thread with a very very very very...')
# self.assertEqual(crumb.text(), 'A thread with a very very very very...')
def test_edit_post_moderator(self):
"""Editing post as a moderator works."""
@ -107,10 +106,10 @@ class PostsTemplateTests(KBForumTestCase):
{"content": "More new content"},
args=[d.slug, t.id, p.id],
)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
edited_p = Post.objects.get(pk=p.pk)
eq_("More new content", edited_p.content)
self.assertEqual("More new content", edited_p.content)
def test_preview_reply(self):
"""Preview a reply."""
@ -127,10 +126,10 @@ class PostsTemplateTests(KBForumTestCase):
{"content": content, "preview": "any string"},
args=[d.slug, t.id],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(content, doc("#post-preview div.content").text())
eq_(num_posts, t.post_set.count())
self.assertEqual(content, doc("#post-preview div.content").text())
self.assertEqual(num_posts, t.post_set.count())
def test_preview_async(self):
"""Preview a reply."""
@ -145,9 +144,9 @@ class PostsTemplateTests(KBForumTestCase):
{"content": content},
args=[d.slug],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(content, doc("div.content").text())
self.assertEqual(content, doc("div.content").text())
def test_watch_thread(self):
"""Watch and unwatch a thread."""
@ -178,7 +177,7 @@ class PostsTemplateTests(KBForumTestCase):
t.new_post(creator=u, content="linking http://test.org")
response = get(self.client, "wiki.discuss.posts", args=[t.document.slug, t.pk])
doc = pq(response.content)
eq_("nofollow", doc("ol.posts div.content a")[0].attrib["rel"])
self.assertEqual("nofollow", doc("ol.posts div.content a")[0].attrib["rel"])
class ThreadsTemplateTests(KBForumTestCase):
@ -193,7 +192,7 @@ class ThreadsTemplateTests(KBForumTestCase):
doc = pq(response.content)
last_post_link = doc("tr.threads td.last-post a:not(.username)")[0]
href = last_post_link.attrib["href"]
eq_(href.split("#")[1], "post-%d" % p2.id)
self.assertEqual(href.split("#")[1], "post-%d" % p2.id)
def test_empty_thread_errors(self):
"""Posting an empty thread shows errors."""
@ -210,8 +209,8 @@ class ThreadsTemplateTests(KBForumTestCase):
doc = pq(response.content)
errors = doc("ul.errorlist li a")
eq_(errors[0].text, "Please provide a title.")
eq_(errors[1].text, "Please provide a message.")
self.assertEqual(errors[0].text, "Please provide a title.")
self.assertEqual(errors[1].text, "Please provide a message.")
def test_new_short_thread_errors(self):
"""Posting a short new thread shows errors."""
@ -228,11 +227,11 @@ class ThreadsTemplateTests(KBForumTestCase):
doc = pq(response.content)
errors = doc("ul.errorlist li a")
eq_(
self.assertEqual(
errors[0].text,
"Your title is too short (4 characters). It must be at least 5 characters.",
)
eq_(
self.assertEqual(
errors[1].text,
"Your message is too short (4 characters). It must be at least 5 characters.",
)
@ -253,7 +252,7 @@ class ThreadsTemplateTests(KBForumTestCase):
doc = pq(response.content)
errors = doc("ul.errorlist li a")
eq_(
self.assertEqual(
errors[0].text,
"Your title is too short (4 characters). It must be at least 5 characters.",
)
@ -267,7 +266,7 @@ class ThreadsTemplateTests(KBForumTestCase):
res = get(self.client, "wiki.discuss.edit_thread", args=[t.document.slug, t.id])
doc = pq(res.content)
eq_(len(doc("form.edit-thread")), 1)
self.assertEqual(len(doc("form.edit-thread")), 1)
def test_watch_forum(self):
"""Watch and unwatch a forum."""
@ -305,7 +304,7 @@ class ThreadsTemplateTests(KBForumTestCase):
response = self.client.get(
reverse("wiki.discuss.threads", args=[r.document.slug], locale="de")
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_all_locale_discussions(self):
"""Start or stop watching all discussions in a locale."""
@ -335,7 +334,7 @@ class ThreadsTemplateTests(KBForumTestCase):
t2.new_post(creator=u, content="last")
self.client.login(username=u.username, password="testpass")
response = post(self.client, "wiki.locale_discussions")
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
title = doc(".threads .title a:first").text()
assert title.startswith("A thread with a very very long")
@ -355,10 +354,10 @@ class NewThreadTemplateTests(KBForumTestCase):
{"title": "Topic", "content": content, "preview": "any string"},
args=[d.slug],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(content, doc("#post-preview div.content").text())
eq_(num_threads, d.thread_set.count())
self.assertEqual(content, doc("#post-preview div.content").text())
self.assertEqual(num_threads, d.thread_set.count())
class FlaggedPostTests(KBForumTestCase):
@ -373,9 +372,9 @@ class FlaggedPostTests(KBForumTestCase):
add_permission(u2, FlaggedObject, "can_moderate")
self.client.login(username=u2.username, password="testpass")
response = get(self.client, "flagit.queue")
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(1, len(doc("#flagged-queue li")))
self.assertEqual(1, len(doc("#flagged-queue li")))
class TestRatelimiting(KBForumTestCase):
@ -393,7 +392,7 @@ class TestRatelimiting(KBForumTestCase):
{"title": "Topic", "content": "hellooo"},
args=[d.slug],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
# Now 3 replies (only 2 should save):
t = Thread.objects.all()[0]
@ -404,7 +403,7 @@ class TestRatelimiting(KBForumTestCase):
{"content": "hellooo"},
args=[d.slug, t.id],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
# And another thread that shouldn't save:
response = post(
@ -415,4 +414,4 @@ class TestRatelimiting(KBForumTestCase):
)
# We should only have 4 posts (each thread and reply creates a post).
eq_(4, Post.objects.count())
self.assertEqual(4, Post.objects.count())

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.kbforums.tests import KBForumTestCase, ThreadFactory
from kitsune.sumo.tests import get, post
from kitsune.users.tests import UserFactory, add_permission
@ -27,36 +25,36 @@ class KBBelongsTestCase(KBForumTestCase):
def test_posts_thread_belongs_to_document(self):
"""Posts view - thread belongs to document."""
r = get(self.client, "wiki.discuss.posts", args=[self.doc_2.slug, self.thread.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_reply_thread_belongs_to_document(self):
"""Reply action - thread belongs to document."""
r = post(self.client, "wiki.discuss.reply", {}, args=[self.doc_2.slug, self.thread.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_locked_thread_belongs_to_document(self):
"""Lock action - thread belongs to document."""
r = post(
self.client, "wiki.discuss.lock_thread", {}, args=[self.doc_2.slug, self.thread.id]
)
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_sticky_thread_belongs_to_document(self):
"""Sticky action - thread belongs to document."""
r = post(
self.client, "wiki.discuss.sticky_thread", {}, args=[self.doc_2.slug, self.thread.id]
)
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_edit_thread_belongs_to_document(self):
"""Edit thread action - thread belongs to document."""
r = get(self.client, "wiki.discuss.edit_thread", args=[self.doc_2.slug, self.thread.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_delete_thread_belongs_to_document(self):
"""Delete thread action - thread belongs to document."""
r = get(self.client, "wiki.discuss.delete_thread", args=[self.doc_2.slug, self.thread.id])
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_edit_post_belongs_to_thread_and_document(self):
"""
@ -68,14 +66,14 @@ class KBBelongsTestCase(KBForumTestCase):
"wiki.discuss.edit_post",
args=[self.doc_2.slug, self.thread.id, self.post.id],
)
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
r = get(
self.client,
"wiki.discuss.edit_post",
args=[self.doc.slug, self.thread_2.id, self.post.id],
)
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
def test_delete_post_belongs_to_thread_and_document(self):
"""
@ -87,11 +85,11 @@ class KBBelongsTestCase(KBForumTestCase):
"wiki.discuss.delete_post",
args=[self.doc_2.slug, self.thread.id, self.post.id],
)
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)
r = get(
self.client,
"wiki.discuss.delete_post",
args=[self.doc.slug, self.thread_2.id, self.post.id],
)
eq_(404, r.status_code)
self.assertEqual(404, r.status_code)

Просмотреть файл

@ -1,8 +1,6 @@
from nose.tools import eq_
from kitsune.kbforums.events import NewPostEvent, NewThreadEvent
from kitsune.kbforums.models import Thread
from kitsune.kbforums.tests import KBForumTestCase, ThreadFactory
from kitsune.kbforums.events import NewThreadEvent, NewPostEvent
from kitsune.sumo.tests import get, post
from kitsune.users.tests import UserFactory, add_permission
from kitsune.wiki.tests import DocumentFactory
@ -60,8 +58,8 @@ class ThreadTests(KBForumTestCase):
)
edited_t = d.thread_set.get(pk=t.id)
eq_("Sticky Thread", t.title)
eq_("A new title", edited_t.title)
self.assertEqual("Sticky Thread", t.title)
self.assertEqual("A new title", edited_t.title)
def test_edit_thread_moderator(self):
"""Editing post as a moderator works."""
@ -71,15 +69,15 @@ class ThreadTests(KBForumTestCase):
d = t.document
self.client.login(username=u.username, password="testpass")
eq_("Sticky Thread", t.title)
self.assertEqual("Sticky Thread", t.title)
r = post(
self.client, "wiki.discuss.edit_thread", {"title": "new title"}, args=[d.slug, t.id]
)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
edited_t = Thread.objects.get(pk=t.id)
eq_("new title", edited_t.title)
self.assertEqual("new title", edited_t.title)
def test_disallowed_404(self):
"""If document.allow_discussion is false, should return 404."""
@ -90,7 +88,7 @@ class ThreadTests(KBForumTestCase):
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))
self.assertEqual(404, st, "%s was %s, not 404" % (url, st))
check("wiki.discuss.threads")
check("wiki.discuss.new_thread")
@ -117,48 +115,48 @@ class ThreadPermissionsTests(KBForumTestCase):
response = get(
self.client, "wiki.discuss.edit_thread", args=[self.doc.slug, self.thread.id]
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_edit_locked_thread_403(self):
"""Editing a locked thread returns 403."""
t = ThreadFactory(document=self.doc, creator=self.u, is_locked=True)
response = get(self.client, "wiki.discuss.edit_thread", args=[self.doc.slug, t.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_delete_thread_403(self):
"""Deleting a thread without permissions returns 403."""
response = get(
self.client, "wiki.discuss.delete_thread", args=[self.doc.slug, self.thread.id]
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_sticky_thread_405(self):
"""Marking a thread sticky with a HTTP GET returns 405."""
response = get(
self.client, "wiki.discuss.sticky_thread", args=[self.doc.slug, self.thread.id]
)
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
def test_sticky_thread_403(self):
"""Marking a thread sticky without permissions returns 403."""
response = post(
self.client, "wiki.discuss.sticky_thread", args=[self.doc.slug, self.thread.id]
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_locked_thread_403(self):
"""Marking a thread locked without permissions returns 403."""
response = post(
self.client, "wiki.discuss.lock_thread", args=[self.doc.slug, self.thread.id]
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_locked_thread_405(self):
"""Marking a thread locked via a GET instead of a POST request."""
response = get(
self.client, "wiki.discuss.lock_thread", args=[self.doc.slug, self.thread.id]
)
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
def test_post_edit_403(self):
"""Editing a post without permissions returns 403."""
@ -167,7 +165,7 @@ class ThreadPermissionsTests(KBForumTestCase):
"wiki.discuss.edit_post",
args=[self.doc.slug, self.thread.id, self.post.id],
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_post_delete_403(self):
"""Deleting a post without permissions returns 403."""
@ -176,4 +174,4 @@ class ThreadPermissionsTests(KBForumTestCase):
"wiki.discuss.delete_post",
args=[self.doc.slug, self.thread.id, self.post.id],
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)

Просмотреть файл

@ -3,7 +3,6 @@ from datetime import date, datetime, timedelta
from django.core.cache import cache
from django.core.management import call_command
from nose.tools import eq_
from kitsune.kpi.models import (
EXIT_SURVEY_DONT_KNOW_CODE,
@ -42,7 +41,7 @@ class KpiApiTests(TestCase):
url = reverse(name)
url = urlparams(url, format="json", **kwargs)
response = self.client.get(url)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
return json.loads(response.content)
def test_questions(self):
@ -59,10 +58,10 @@ class KpiApiTests(TestCase):
QuestionFactory(is_locked=True)
r = self._get_api_result("api.kpi.questions")
eq_(r["objects"][0]["solved"], 1)
eq_(r["objects"][0]["responded_24"], 2)
eq_(r["objects"][0]["responded_72"], 2)
eq_(r["objects"][0]["questions"], 3)
self.assertEqual(r["objects"][0]["solved"], 1)
self.assertEqual(r["objects"][0]["responded_24"], 2)
self.assertEqual(r["objects"][0]["responded_72"], 2)
self.assertEqual(r["objects"][0]["questions"], 3)
def test_questions_by_locale(self):
"""Test locale filtering of questions API call."""
@ -82,21 +81,21 @@ class KpiApiTests(TestCase):
# Verify no locale filtering:
r = self._get_api_result("api.kpi.questions")
eq_(r["objects"][0]["solved"], 1)
eq_(r["objects"][0]["responded_24"], 2)
eq_(r["objects"][0]["responded_72"], 2)
eq_(r["objects"][0]["questions"], 4)
self.assertEqual(r["objects"][0]["solved"], 1)
self.assertEqual(r["objects"][0]["responded_24"], 2)
self.assertEqual(r["objects"][0]["responded_72"], 2)
self.assertEqual(r["objects"][0]["questions"], 4)
# Verify locale=en-US
r = self._get_api_result("api.kpi.questions", locale="en-US")
eq_(r["objects"][0]["solved"], 1)
eq_(r["objects"][0]["responded_24"], 2)
eq_(r["objects"][0]["responded_72"], 2)
eq_(r["objects"][0]["questions"], 3)
self.assertEqual(r["objects"][0]["solved"], 1)
self.assertEqual(r["objects"][0]["responded_24"], 2)
self.assertEqual(r["objects"][0]["responded_72"], 2)
self.assertEqual(r["objects"][0]["questions"], 3)
# Verify locale=pt-BR
r = self._get_api_result("api.kpi.questions", locale="pt-BR")
eq_(r["objects"][0]["questions"], 1)
self.assertEqual(r["objects"][0]["questions"], 1)
assert "solved" not in r["objects"][0]
assert "responded_24" not in r["objects"][0]
assert "responded_72" not in r["objects"][0]
@ -124,21 +123,21 @@ class KpiApiTests(TestCase):
# Verify no product filtering:
r = self._get_api_result("api.kpi.questions")
eq_(r["objects"][0]["solved"], 1)
eq_(r["objects"][0]["responded_24"], 2)
eq_(r["objects"][0]["responded_72"], 2)
eq_(r["objects"][0]["questions"], 4)
self.assertEqual(r["objects"][0]["solved"], 1)
self.assertEqual(r["objects"][0]["responded_24"], 2)
self.assertEqual(r["objects"][0]["responded_72"], 2)
self.assertEqual(r["objects"][0]["questions"], 4)
# Verify product=firefox-os
r = self._get_api_result("api.kpi.questions", product="firefox-os")
eq_(r["objects"][0]["solved"], 1)
eq_(r["objects"][0]["responded_24"], 2)
eq_(r["objects"][0]["responded_72"], 2)
eq_(r["objects"][0]["questions"], 3)
self.assertEqual(r["objects"][0]["solved"], 1)
self.assertEqual(r["objects"][0]["responded_24"], 2)
self.assertEqual(r["objects"][0]["responded_72"], 2)
self.assertEqual(r["objects"][0]["questions"], 3)
# Verify product=firefox
r = self._get_api_result("api.kpi.questions", product="firefox")
eq_(r["objects"][0]["questions"], 1)
self.assertEqual(r["objects"][0]["questions"], 1)
assert "solved" not in r["objects"][0]
assert "responded_24" not in r["objects"][0]
assert "responded_72" not in r["objects"][0]
@ -152,7 +151,7 @@ class KpiApiTests(TestCase):
QuestionFactory(creator=u)
r = self._get_api_result("api.kpi.questions")
eq_(len(r["objects"]), 0)
self.assertEqual(len(r["objects"]), 0)
# Activate the user, now the questions should count.
u.is_active = True
@ -161,9 +160,9 @@ class KpiApiTests(TestCase):
url = reverse("api.kpi.questions")
response = self.client.get(url + "?format=json")
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
r = json.loads(response.content)
eq_(r["objects"][0]["questions"], 2)
self.assertEqual(r["objects"][0]["questions"], 2)
def test_vote(self):
"""Test vote API call."""
@ -178,10 +177,10 @@ class KpiApiTests(TestCase):
AnswerVoteFactory(answer=a, helpful=True)
r = self._get_api_result("api.kpi.votes")
eq_(r["objects"][0]["kb_helpful"], 1)
eq_(r["objects"][0]["kb_votes"], 3)
eq_(r["objects"][0]["ans_helpful"], 2)
eq_(r["objects"][0]["ans_votes"], 3)
self.assertEqual(r["objects"][0]["kb_helpful"], 1)
self.assertEqual(r["objects"][0]["kb_votes"], 3)
self.assertEqual(r["objects"][0]["ans_helpful"], 2)
self.assertEqual(r["objects"][0]["ans_votes"], 3)
def test_kb_vote(self):
"""Test vote API call."""
@ -202,33 +201,33 @@ class KpiApiTests(TestCase):
# All votes should be counted if we don't specify a locale
r = self._get_api_result("api.kpi.kb-votes")
eq_(r["objects"][0]["kb_helpful"], 3)
eq_(r["objects"][0]["kb_votes"], 9)
self.assertEqual(r["objects"][0]["kb_helpful"], 3)
self.assertEqual(r["objects"][0]["kb_votes"], 9)
# Only en-US votes:
r = self._get_api_result("api.kpi.kb-votes", locale="en-US")
eq_(r["objects"][0]["kb_helpful"], 1)
eq_(r["objects"][0]["kb_votes"], 3)
self.assertEqual(r["objects"][0]["kb_helpful"], 1)
self.assertEqual(r["objects"][0]["kb_votes"], 3)
# Only es votes:
r = self._get_api_result("api.kpi.kb-votes", locale="es")
eq_(r["objects"][0]["kb_helpful"], 2)
eq_(r["objects"][0]["kb_votes"], 6)
self.assertEqual(r["objects"][0]["kb_helpful"], 2)
self.assertEqual(r["objects"][0]["kb_votes"], 6)
# Only Firefox OS votes:
r = self._get_api_result("api.kpi.kb-votes", product="firefox-os")
eq_(r["objects"][0]["kb_helpful"], 2)
eq_(r["objects"][0]["kb_votes"], 6)
self.assertEqual(r["objects"][0]["kb_helpful"], 2)
self.assertEqual(r["objects"][0]["kb_votes"], 6)
# Only Firefox votes:
r = self._get_api_result("api.kpi.kb-votes", product="firefox")
eq_(r["objects"][0]["kb_helpful"], 1)
eq_(r["objects"][0]["kb_votes"], 3)
self.assertEqual(r["objects"][0]["kb_helpful"], 1)
self.assertEqual(r["objects"][0]["kb_votes"], 3)
# Only Firefox OS + es votes:
r = self._get_api_result("api.kpi.kb-votes", product="firefox-os", locale="es")
eq_(r["objects"][0]["kb_helpful"], 1)
eq_(r["objects"][0]["kb_votes"], 3)
self.assertEqual(r["objects"][0]["kb_helpful"], 1)
self.assertEqual(r["objects"][0]["kb_votes"], 3)
def test_active_contributors(self):
"""Test active contributors API call."""
@ -261,9 +260,9 @@ class KpiApiTests(TestCase):
r = self._get_api_result("api.kpi.contributors")
eq_(r["objects"][0]["en_us"], 2)
eq_(r["objects"][0]["non_en_us"], 2)
eq_(r["objects"][0]["support_forum"], 1)
self.assertEqual(r["objects"][0]["en_us"], 2)
self.assertEqual(r["objects"][0]["non_en_us"], 2)
self.assertEqual(r["objects"][0]["support_forum"], 1)
def test_asker_replies_arent_a_contribution(self):
"""Verify that replies posted by the question creator aren't counted.
@ -282,7 +281,7 @@ class KpiApiTests(TestCase):
call_command("update_contributor_metrics", str(date.today() + timedelta(days=1)))
r = self._get_api_result("api.kpi.contributors")
eq_(r["objects"][0]["support_forum"], 0)
self.assertEqual(r["objects"][0]["support_forum"], 0)
# Change the question creator, now we should have 1 contributor.
q.creator = UserFactory()
@ -293,7 +292,7 @@ class KpiApiTests(TestCase):
call_command("update_contributor_metrics", str(date.today() + timedelta(days=1)))
r = self._get_api_result("api.kpi.contributors")
eq_(r["objects"][0]["support_forum"], 1)
self.assertEqual(r["objects"][0]["support_forum"], 1)
def test_elastic_clickthrough_get(self):
"""Test elastic clickthrough read API."""
@ -306,7 +305,7 @@ class KpiApiTests(TestCase):
url = reverse("api.kpi.search-ctr")
response = self.client.get(url + "?format=json")
data = json.loads(response.content)
eq_(
self.assertEqual(
data["objects"],
[
{"clicks": 2, "searches": 20, "start": "2000-01-09"},
@ -317,7 +316,7 @@ class KpiApiTests(TestCase):
# Test filtering by start date:
response = self.client.get(url + "?format=json&min_start=2000-01-09")
data = json.loads(response.content)
eq_(data["objects"], [{"searches": 20, "start": "2000-01-09", "clicks": 2}])
self.assertEqual(data["objects"], [{"searches": 20, "start": "2000-01-09", "clicks": 2}])
def test_visitors(self):
"""Test unique visitors API call."""
@ -327,7 +326,7 @@ class KpiApiTests(TestCase):
# There should be 42 visitors.
r = self._get_api_result("api.kpi.visitors")
eq_(r["objects"][0]["visitors"], 42)
self.assertEqual(r["objects"][0]["visitors"], 42)
def test_l10n_coverage(self):
"""Test l10n coverage API call."""
@ -337,7 +336,7 @@ class KpiApiTests(TestCase):
# The l10n coverage should be 56%.
r = self._get_api_result("api.kpi.l10n-coverage")
eq_(r["objects"][0]["coverage"], 56)
self.assertEqual(r["objects"][0]["coverage"], 56)
def test_exit_survey_results(self):
"""Test the exist survey results API call."""
@ -351,6 +350,6 @@ class KpiApiTests(TestCase):
# Verify the results returned from the API
r = self._get_api_result("api.kpi.exit-survey")
eq_(r["objects"][0]["yes"], 1337)
eq_(r["objects"][0]["no"], 42)
eq_(r["objects"][0]["dont_know"], 777)
self.assertEqual(r["objects"][0]["yes"], 1337)
self.assertEqual(r["objects"][0]["no"], 42)
self.assertEqual(r["objects"][0]["dont_know"], 777)

Просмотреть файл

@ -1,8 +1,7 @@
from datetime import date, datetime, timedelta
from unittest.mock import patch
from django.core.management import call_command
from unittest.mock import patch
from nose.tools import eq_
import kitsune.kpi.management.utils
from kitsune.kpi import surveygizmo_utils
@ -76,85 +75,85 @@ class CohortAnalysisTests(TestCase):
def test_contributor_cohort_analysis(self):
c1 = Cohort.objects.get(kind__code=CONTRIBUTOR_COHORT_CODE, start=self.start_of_first_week)
eq_(c1.size, 8)
self.assertEqual(c1.size, 8)
c1r1 = c1.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=1))
eq_(c1r1.size, 2)
self.assertEqual(c1r1.size, 2)
c1r2 = c1.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=2))
eq_(c1r2.size, 3)
self.assertEqual(c1r2.size, 3)
c2 = Cohort.objects.get(
kind__code=CONTRIBUTOR_COHORT_CODE, start=self.start_of_first_week + timedelta(weeks=1)
)
eq_(c2.size, 8)
self.assertEqual(c2.size, 8)
c2r1 = c2.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=2))
eq_(c2r1.size, 2)
self.assertEqual(c2r1.size, 2)
def test_kb_enus_contributor_cohort_analysis(self):
c1 = Cohort.objects.get(
kind__code=KB_ENUS_CONTRIBUTOR_COHORT_CODE, start=self.start_of_first_week
)
eq_(c1.size, 5)
self.assertEqual(c1.size, 5)
c1r1 = c1.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=1))
eq_(c1r1.size, 2)
self.assertEqual(c1r1.size, 2)
c1r2 = c1.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=2))
eq_(c1r2.size, 0)
self.assertEqual(c1r2.size, 0)
c2 = Cohort.objects.get(
kind__code=KB_ENUS_CONTRIBUTOR_COHORT_CODE,
start=self.start_of_first_week + timedelta(weeks=1),
)
eq_(c2.size, 1)
self.assertEqual(c2.size, 1)
c2r1 = c2.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=2))
eq_(c2r1.size, 0)
self.assertEqual(c2r1.size, 0)
def test_kb_l10n_contributor_cohort_analysis(self):
c1 = Cohort.objects.get(
kind__code=KB_L10N_CONTRIBUTOR_COHORT_CODE, start=self.start_of_first_week
)
eq_(c1.size, 3)
self.assertEqual(c1.size, 3)
c1r1 = c1.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=1))
eq_(c1r1.size, 0)
self.assertEqual(c1r1.size, 0)
c1r2 = c1.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=2))
eq_(c1r2.size, 3)
self.assertEqual(c1r2.size, 3)
c2 = Cohort.objects.get(
kind__code=KB_L10N_CONTRIBUTOR_COHORT_CODE,
start=self.start_of_first_week + timedelta(weeks=1),
)
eq_(c2.size, 0)
self.assertEqual(c2.size, 0)
c2r1 = c2.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=2))
eq_(c2r1.size, 0)
self.assertEqual(c2r1.size, 0)
def test_support_forum_helper_cohort_analysis(self):
c1 = Cohort.objects.get(
kind__code=SUPPORT_FORUM_HELPER_COHORT_CODE, start=self.start_of_first_week
)
eq_(c1.size, 0)
self.assertEqual(c1.size, 0)
c1r1 = c1.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=1))
eq_(c1r1.size, 0)
self.assertEqual(c1r1.size, 0)
c2 = Cohort.objects.get(
kind__code=SUPPORT_FORUM_HELPER_COHORT_CODE,
start=self.start_of_first_week + timedelta(weeks=1),
)
eq_(c2.size, 7)
self.assertEqual(c2.size, 7)
c2r1 = c2.retention_metrics.get(start=self.start_of_first_week + timedelta(weeks=2))
eq_(c2r1.size, 2)
self.assertEqual(c2r1.size, 2)
class CronJobTests(TestCase):
@ -167,10 +166,10 @@ class CronJobTests(TestCase):
call_command("update_visitors_metric")
metrics = Metric.objects.filter(kind=visitor_kind).order_by("start")
eq_(3, len(metrics))
eq_(42, metrics[0].value)
eq_(193, metrics[1].value)
eq_(date(2012, 1, 15), metrics[2].start)
self.assertEqual(3, len(metrics))
self.assertEqual(42, metrics[0].value)
self.assertEqual(193, metrics[1].value)
self.assertEqual(date(2012, 1, 15), metrics[2].start)
@patch.object(kitsune.kpi.management.utils, "_get_top_docs")
@patch.object(googleanalytics, "visitors_by_locale")
@ -204,8 +203,8 @@ class CronJobTests(TestCase):
# Value should be 75% (1/1 * 25/100 + 1/1 * 50/100)
call_command("update_l10n_metric")
metrics = Metric.objects.filter(kind=l10n_kind)
eq_(1, len(metrics))
eq_(75, metrics[0].value)
self.assertEqual(1, len(metrics))
self.assertEqual(75, metrics[0].value)
# Create a new revision with TYPO_SIGNIFICANCE. It shouldn't
# affect the results.
@ -215,8 +214,8 @@ class CronJobTests(TestCase):
Metric.objects.all().delete()
call_command("update_l10n_metric")
metrics = Metric.objects.filter(kind=l10n_kind)
eq_(1, len(metrics))
eq_(75, metrics[0].value)
self.assertEqual(1, len(metrics))
self.assertEqual(75, metrics[0].value)
# Create a new revision with MEDIUM_SIGNIFICANCE. The coverage
# should now be 62% (0.5/1 * 25/100 + 1/1 * 50/100)
@ -226,8 +225,8 @@ class CronJobTests(TestCase):
Metric.objects.all().delete()
call_command("update_l10n_metric")
metrics = Metric.objects.filter(kind=l10n_kind)
eq_(1, len(metrics))
eq_(62, metrics[0].value)
self.assertEqual(1, len(metrics))
self.assertEqual(62, metrics[0].value)
# And another new revision with MEDIUM_SIGNIFICANCE makes the
# coverage 50% (1/1 * 50/100).
@ -237,8 +236,8 @@ class CronJobTests(TestCase):
Metric.objects.all().delete()
call_command("update_l10n_metric")
metrics = Metric.objects.filter(kind=l10n_kind)
eq_(1, len(metrics))
eq_(50, metrics[0].value)
self.assertEqual(1, len(metrics))
self.assertEqual(50, metrics[0].value)
# If we remove the two MEDIUM_SIGNIFICANCE revisions and add a
# MAJOR_SIGNIFICANCE revision, the coverage is 50% as well.
@ -250,8 +249,8 @@ class CronJobTests(TestCase):
Metric.objects.all().delete()
call_command("update_l10n_metric")
metrics = Metric.objects.filter(kind=l10n_kind)
eq_(1, len(metrics))
eq_(50, metrics[0].value)
self.assertEqual(1, len(metrics))
self.assertEqual(50, metrics[0].value)
@patch.object(googleanalytics, "search_ctr")
def test_update_search_ctr(self, search_ctr):
@ -267,10 +266,10 @@ class CronJobTests(TestCase):
call_command("update_search_ctr_metric")
metrics = Metric.objects.filter(kind=clicks_kind).order_by("start")
eq_(3, len(metrics))
eq_(421, metrics[0].value)
eq_(138, metrics[1].value)
eq_(date(2013, 6, 8), metrics[2].start)
self.assertEqual(3, len(metrics))
self.assertEqual(421, metrics[0].value)
self.assertEqual(138, metrics[1].value)
self.assertEqual(date(2013, 6, 8), metrics[2].start)
@patch.object(surveygizmo_utils, "requests")
def test_process_exit_surveys(self, requests):
@ -291,10 +290,10 @@ class CronJobTests(TestCase):
kitsune.kpi.management.utils._process_exit_survey_results()
# Verify.
eq_(4, Metric.objects.count())
eq_(2, Metric.objects.filter(kind=yes_kind)[1].value)
eq_(1, Metric.objects.get(kind=no_kind).value)
eq_(1, Metric.objects.get(kind=dunno_kind).value)
self.assertEqual(4, Metric.objects.count())
self.assertEqual(2, Metric.objects.filter(kind=yes_kind)[1].value)
self.assertEqual(1, Metric.objects.get(kind=no_kind).value)
self.assertEqual(1, Metric.objects.get(kind=dunno_kind).value)
SURVEY_GIZMO_EXIT_SURVEY_RESPONSE = """

Просмотреть файл

@ -1,7 +1,5 @@
from datetime import datetime
from unittest.mock import patch
from nose.tools import eq_, ok_
from kitsune.kpi.surveygizmo_utils import (
add_email_to_campaign,
@ -21,8 +19,8 @@ class GetEmailAddressesTests(TestCase):
with self.settings(SURVEYGIZMO_API_TOKEN=None, SURVEYGIZMO_API_TOKEN_SECRET=None):
emails = get_email_addresses("general", datetime(2016, 1, 1), datetime(2016, 1, 2))
eq_(emails, [])
ok_(not mock_requests.get.called)
self.assertEqual(emails, [])
assert not mock_requests.get.called
@patch("kitsune.kpi.surveygizmo_utils.requests")
def test_creds(self, mock_requests):
@ -37,8 +35,8 @@ class GetEmailAddressesTests(TestCase):
)
url = mock_requests.get.call_args[0][0]
ok_("api_token=mytoken" in url)
ok_("api_token_secret=mysecret" in url)
assert "api_token=mytoken" in url
assert "api_token_secret=mysecret" in url
class AddEmailToCampaignTests(TestCase):
@ -50,7 +48,7 @@ class AddEmailToCampaignTests(TestCase):
"""
with self.settings(SURVEYGIZMO_API_TOKEN=None, SURVEYGIZMO_API_TOKEN_SECRET=None):
add_email_to_campaign("general", "a@example.com")
ok_(not mock_requests.put.called)
assert not mock_requests.put.called
@patch("kitsune.kpi.surveygizmo_utils.requests")
def test_creds(self, mock_requests):
@ -61,8 +59,8 @@ class AddEmailToCampaignTests(TestCase):
add_email_to_campaign("general", "a@example.com")
url = mock_requests.put.call_args[0][0]
ok_("api_token=mytoken" in url)
ok_("api_token_secret=mysecret" in url)
assert "api_token=mytoken" in url
assert "api_token_secret=mysecret" in url
class GetExitSurveyResults(TestCase):
@ -74,8 +72,8 @@ class GetExitSurveyResults(TestCase):
"""
with self.settings(SURVEYGIZMO_API_TOKEN=None, SURVEYGIZMO_API_TOKEN_SECRET=None):
summary = get_exit_survey_results("general", datetime(2016, 1, 1))
eq_(summary, {"yes": 0, "no": 0, "dont-know": 0})
ok_(not mock_requests.put.called)
self.assertEqual(summary, {"yes": 0, "no": 0, "dont-know": 0})
assert not mock_requests.put.called
@patch("kitsune.kpi.surveygizmo_utils.requests")
def test_creds(self, mock_requests):
@ -88,8 +86,8 @@ class GetExitSurveyResults(TestCase):
get_exit_survey_results("general", datetime(2016, 1, 1))
url = mock_requests.get.call_args[0][0]
ok_("api_token=mytoken" in url)
ok_("api_token_secret=mysecret" in url)
assert "api_token=mytoken" in url
assert "api_token_secret=mysecret" in url
SURVEY_GIZMO_EMPTY_RESPONSE = """

Просмотреть файл

@ -1,4 +1,3 @@
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.products.tests import ProductFactory
@ -17,6 +16,6 @@ class HomeTestCase(Elastic7TestCase):
# GET the home page and verify the content
r = self.client.get(reverse("home"), follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(4, len(doc("#products-and-services li")))
self.assertEqual(4, len(doc("#products-and-services li")))

Просмотреть файл

@ -1,10 +1,7 @@
from nose.tools import eq_
from testfixtures import LogCapture
from django.test.utils import override_settings
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail import EmailMessage
from django.core.mail.backends.base import BaseEmailBackend
from django.test.utils import override_settings
from testfixtures import LogCapture
from kitsune.lib.email import LoggingEmailBackend
from kitsune.sumo.tests import TestCase
@ -104,7 +101,7 @@ class TestLoggingEmailBackend(TestCase):
def test_fail_silently(self):
# Make sure fail_silently is passed through to the real backend.
logging_backend = LoggingEmailBackend(fail_silently=True)
eq_(logging_backend.real_backend.fail_silently, True)
self.assertEqual(logging_backend.real_backend.fail_silently, True)
# The below tests validate several things in 3 cases. The 3 cases are:
#
@ -131,20 +128,20 @@ class TestLoggingEmailBackend(TestCase):
# setup and make sure we have the right mock backend
logging_backend = LoggingEmailBackend()
batch_id = logging_backend.batch_id
eq_(logging_backend.real_backend.__class__, SucceedingMockEmailBackend)
eq_(logging_backend.real_backend._is_open, False)
eq_(logging_backend.real_backend._sent_messages, False)
self.assertEqual(logging_backend.real_backend.__class__, SucceedingMockEmailBackend)
self.assertEqual(logging_backend.real_backend._is_open, False)
self.assertEqual(logging_backend.real_backend._sent_messages, False)
# Open a connection
eq_(logging_backend.open(), True)
self.assertEqual(logging_backend.open(), True)
self.expect_log("Batch %i - Succesfully opened new connection." % (batch_id,))
eq_(logging_backend.real_backend._is_open, True)
self.assertEqual(logging_backend.real_backend._is_open, True)
# Send 3 messages
messages = [
EmailMessage(subject="subject%i" % i, to=["%i@example.com" % i]) for i in range(3)
]
eq_(logging_backend.send_messages(messages), 3)
self.assertEqual(logging_backend.send_messages(messages), 3)
log_msg = (
"Batch %i - Attempting to send 3 emails: subject0 - '0@example.com'\n"
"\tsubject1 - '1@example.com'\n"
@ -152,12 +149,12 @@ class TestLoggingEmailBackend(TestCase):
)
self.expect_log(log_msg, check=False)
self.expect_log("Batch %i - Succesfully sent 3 emails." % (batch_id,))
eq_(logging_backend.real_backend._sent_messages, True)
self.assertEqual(logging_backend.real_backend._sent_messages, True)
# Close
eq_(logging_backend.close(), None)
self.assertEqual(logging_backend.close(), None)
self.expect_log("Batch %i - Closed connection." % (batch_id,))
eq_(logging_backend.real_backend._is_open, False)
self.assertEqual(logging_backend.real_backend._is_open, False)
@override_settings(
EMAIL_LOGGING_REAL_BACKEND="kitsune.lib.tests.test_email.FailingMockEmailBackend"
@ -166,22 +163,22 @@ class TestLoggingEmailBackend(TestCase):
# Setup and make sure we have the right mock backend
logging_backend = LoggingEmailBackend()
batch_id = logging_backend.batch_id
eq_(logging_backend.real_backend.__class__, FailingMockEmailBackend)
eq_(logging_backend.real_backend._is_open, False)
eq_(logging_backend.real_backend._sent_messages, False)
self.assertEqual(logging_backend.real_backend.__class__, FailingMockEmailBackend)
self.assertEqual(logging_backend.real_backend._is_open, False)
self.assertEqual(logging_backend.real_backend._sent_messages, False)
# Open a connection
eq_(logging_backend.open(), False)
self.assertEqual(logging_backend.open(), False)
self.expect_log(
"Batch %i - Did not open a new connection. (Either cached or failed)" % (batch_id,)
)
eq_(logging_backend.real_backend._is_open, True)
self.assertEqual(logging_backend.real_backend._is_open, True)
# Send 3 messages
messages = [
EmailMessage(subject="subject%i" % i, to=["%i@example.com" % i]) for i in range(3)
]
eq_(logging_backend.send_messages(messages), 0)
self.assertEqual(logging_backend.send_messages(messages), 0)
log_msg = (
"Batch %i - Attempting to send 3 emails: subject0 - '0@example.com'\n"
"\tsubject1 - '1@example.com'\n"
@ -191,12 +188,12 @@ class TestLoggingEmailBackend(TestCase):
self.expect_log(
"Batch %i - Failed to send all emails. Sent 0 out of 3." % (batch_id,), level="ERROR"
)
eq_(logging_backend.real_backend._sent_messages, True)
self.assertEqual(logging_backend.real_backend._sent_messages, True)
# Close
eq_(logging_backend.close(), None)
self.assertEqual(logging_backend.close(), None)
self.expect_log("Batch %i - Closed connection." % (batch_id,))
eq_(logging_backend.real_backend._is_open, False)
self.assertEqual(logging_backend.real_backend._is_open, False)
@override_settings(
EMAIL_LOGGING_REAL_BACKEND="kitsune.lib.tests.test_email.FlakyMockEmailBackend"
@ -205,20 +202,20 @@ class TestLoggingEmailBackend(TestCase):
# Setup and make sure we have the right mock backend
logging_backend = LoggingEmailBackend()
batch_id = logging_backend.batch_id
eq_(logging_backend.real_backend.__class__, FlakyMockEmailBackend)
eq_(logging_backend.real_backend._is_open, False)
eq_(logging_backend.real_backend._sent_messages, False)
self.assertEqual(logging_backend.real_backend.__class__, FlakyMockEmailBackend)
self.assertEqual(logging_backend.real_backend._is_open, False)
self.assertEqual(logging_backend.real_backend._sent_messages, False)
# Open a connection
eq_(logging_backend.open(), None)
self.assertEqual(logging_backend.open(), None)
self.expect_log("Batch %i - Opened a new connection. (Unknown status)" % (batch_id,))
eq_(logging_backend.real_backend._is_open, True)
self.assertEqual(logging_backend.real_backend._is_open, True)
# Send 3 messages
messages = [
EmailMessage(subject="subject%i" % i, to=["%i@example.com" % i]) for i in range(3)
]
eq_(logging_backend.send_messages(messages), 1)
self.assertEqual(logging_backend.send_messages(messages), 1)
log_msg = (
"Batch %i - Attempting to send 3 emails: subject0 - '0@example.com'\n"
"\tsubject1 - '1@example.com'\n"
@ -228,9 +225,9 @@ class TestLoggingEmailBackend(TestCase):
self.expect_log(
"Batch %i - Failed to send all emails. Sent 1 out of 3." % (batch_id,), level="ERROR"
)
eq_(logging_backend.real_backend._sent_messages, True)
self.assertEqual(logging_backend.real_backend._sent_messages, True)
# Close
eq_(logging_backend.close(), None)
self.assertEqual(logging_backend.close(), None)
self.expect_log("Batch %i - Closed connection." % (batch_id,))
eq_(logging_backend.real_backend._is_open, False)
self.assertEqual(logging_backend.real_backend._is_open, False)

Просмотреть файл

@ -1,9 +1,8 @@
from unittest import mock
from django.contrib.auth.models import AnonymousUser
from django.test.client import RequestFactory
from unittest import mock
from nose.tools import eq_
from kitsune.messages import context_processors
from kitsune.messages.context_processors import unread_message_count
from kitsune.sumo.tests import TestCase
@ -20,7 +19,7 @@ class UnreadCountTests(TestCase):
rf = RequestFactory()
request = rf.get("/")
request.user = AnonymousUser()
eq_(0, unread_message_count(request)["unread_message_count"])
self.assertEqual(0, unread_message_count(request)["unread_message_count"])
assert not unread_count_for.called
@mock.patch.object(context_processors, "unread_count_for")
@ -30,5 +29,5 @@ class UnreadCountTests(TestCase):
rf = RequestFactory()
request = rf.get("/")
request.user = UserFactory()
eq_(3, unread_message_count(request)["unread_message_count"])
self.assertEqual(3, unread_message_count(request)["unread_message_count"])
assert unread_count_for.called

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.messages.models import InboxMessage, OutboxMessage
from kitsune.messages.utils import send_message
from kitsune.sumo.tests import TestCase
@ -17,14 +15,14 @@ class SendTests(TestCase):
msgs_in = InboxMessage.objects.all()
msgs_out = OutboxMessage.objects.all()
eq_(1, msgs_out.count())
self.assertEqual(1, msgs_out.count())
msg_out = msgs_out[0]
eq_(sender, msg_out.sender)
eq_(msg_text, msg_out.message)
self.assertEqual(sender, msg_out.sender)
self.assertEqual(msg_text, msg_out.message)
for u in msg_out.to.all():
assert u in to
eq_(2, msgs_in.count())
self.assertEqual(2, msgs_in.count())
for message in msgs_in:
eq_(sender, message.sender)
self.assertEqual(sender, message.sender)
assert message.to in to
eq_(msg_text, message.message)
self.assertEqual(msg_text, message.message)

Просмотреть файл

@ -1,4 +1,3 @@
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.messages.models import OutboxMessage
@ -19,16 +18,16 @@ class SendMessageTestCase(TestCase):
def test_send_message_page(self):
# Make sure page loads.
response = self.client.get(reverse("messages.new"), follow=True)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
assert len(pq(response.content)("#id_message"))
def _test_send_message_to(self, to):
# Post a new message and verify it was sent.
data = {"to": to, "message": "hi there"}
response = self.client.post(reverse("messages.new", locale="en-US"), data, follow=True)
eq_(200, response.status_code)
eq_("Your message was sent!", pq(response.content)("ul.user-messages").text())
eq_(1, OutboxMessage.objects.filter(sender=self.user1).count())
self.assertEqual(200, response.status_code)
self.assertEqual("Your message was sent!", pq(response.content)("ul.user-messages").text())
self.assertEqual(1, OutboxMessage.objects.filter(sender=self.user1).count())
return response
def test_send_message_to_one(self):
@ -47,8 +46,8 @@ class SendMessageTestCase(TestCase):
def test_send_message_to_prefilled(self):
url = urlparams(reverse("messages.new"), to=self.user2.username)
response = self.client.get(url, follow=True)
eq_(200, response.status_code)
eq_(self.user2.username, pq(response.content)("#id_to")[0].attrib["value"])
self.assertEqual(200, response.status_code)
self.assertEqual(self.user2.username, pq(response.content)("#id_to")[0].attrib["value"])
def test_send_message_ratelimited(self):
"""Verify that after 50 messages, no more are sent."""
@ -60,7 +59,7 @@ class SendMessageTestCase(TestCase):
)
# Verify only 50 are sent.
eq_(50, OutboxMessage.objects.filter(sender=self.user1).count())
self.assertEqual(50, OutboxMessage.objects.filter(sender=self.user1).count())
class MessagePreviewTests(TestCase):
@ -78,6 +77,6 @@ class MessagePreviewTests(TestCase):
{"content": "=Test Content="},
follow=True,
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_("Test Content", doc("div.message h1").text())
self.assertEqual("Test Content", doc("div.message h1").text())

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.messages.models import InboxMessage, OutboxMessage
from kitsune.sumo.tests import LocalizingClient, TestCase
from kitsune.sumo.urlresolvers import reverse
@ -20,7 +18,7 @@ class ReadMessageTests(TestCase):
assert not j.read
url = reverse("messages.bulk_action", locale="en-US")
resp = self.client.post(url, {"id": [i.pk, j.pk], "mark_read": True}, follow=True)
eq_(200, resp.status_code)
self.assertEqual(200, resp.status_code)
assert InboxMessage.objects.get(pk=i.pk).read
assert InboxMessage.objects.get(pk=j.pk).read
@ -34,14 +32,14 @@ class ReadMessageTests(TestCase):
i = InboxMessage.objects.create(sender=self.user2, to=self.user1, message="foo")
assert not i.read
resp = self.client.get(reverse("messages.read", args=[i.pk]), follow=True)
eq_(200, resp.status_code)
self.assertEqual(200, resp.status_code)
assert InboxMessage.objects.get(pk=i.pk).read
def test_unread_does_not_pin(self):
i = InboxMessage.objects.create(sender=self.user2, to=self.user1, message="foo", read=True)
assert i.read
resp = self.client.get(reverse("messages.read", args=[i.pk]), follow=True)
eq_(200, resp.status_code)
self.assertEqual(200, resp.status_code)
assert InboxMessage.objects.get(pk=i.pk).read
def test_mark_message_replied(self):
@ -63,37 +61,37 @@ class DeleteMessageTests(TestCase):
def test_delete_inbox_message(self):
i = InboxMessage.objects.create(sender=self.user2, to=self.user1, message="foo")
eq_(1, InboxMessage.objects.count())
self.assertEqual(1, InboxMessage.objects.count())
resp = self.client.post(
reverse("messages.delete", args=[i.pk], locale="en-US"),
{"confirmed": True},
follow=True,
)
eq_(200, resp.status_code)
eq_(0, InboxMessage.objects.count())
self.assertEqual(200, resp.status_code)
self.assertEqual(0, InboxMessage.objects.count())
def test_delete_many_message(self):
i = InboxMessage.objects.create(to=self.user1, sender=self.user2, message="foo")
j = InboxMessage.objects.create(to=self.user1, sender=self.user2, message="foo")
eq_(2, InboxMessage.objects.count())
self.assertEqual(2, InboxMessage.objects.count())
url = reverse("messages.bulk_action", locale="en-US")
resp = self.client.post(
url, {"id": [i.pk, j.pk], "delete": True, "confirmed": True}, follow=True
)
eq_(200, resp.status_code)
eq_(0, InboxMessage.objects.count())
self.assertEqual(200, resp.status_code)
self.assertEqual(0, InboxMessage.objects.count())
def test_delete_outbox_message(self):
i = OutboxMessage.objects.create(sender=self.user1, message="foo")
i.to.add(self.user2)
eq_(1, OutboxMessage.objects.count())
self.assertEqual(1, OutboxMessage.objects.count())
resp = self.client.post(
reverse("messages.delete_outbox", args=[i.pk], locale="en-US"),
{"confirmed": True},
follow=True,
)
eq_(200, resp.status_code)
eq_(0, OutboxMessage.objects.count())
self.assertEqual(200, resp.status_code)
self.assertEqual(0, OutboxMessage.objects.count())
def test_bulk_delete_none(self):
url = reverse("messages.bulk_action", locale="en-US")
@ -113,19 +111,19 @@ class OutboxTests(TestCase):
def test_message_without_recipients(self):
OutboxMessage.objects.create(sender=self.user1, message="foo")
eq_(1, OutboxMessage.objects.count())
self.assertEqual(1, OutboxMessage.objects.count())
resp = self.client.post(reverse("messages.outbox"), follow=True)
eq_(200, resp.status_code)
self.assertEqual(200, resp.status_code)
def test_delete_many_outbox_message(self):
i = OutboxMessage.objects.create(sender=self.user1, message="foo")
i.to.add(self.user2)
j = OutboxMessage.objects.create(sender=self.user1, message="foo")
j.to.add(self.user2)
eq_(2, OutboxMessage.objects.count())
self.assertEqual(2, OutboxMessage.objects.count())
url = reverse("messages.outbox_bulk_action", locale="en-US")
resp = self.client.post(
url, {"id": [i.pk, j.pk], "delete": True, "confirmed": True}, follow=True
)
eq_(200, resp.status_code)
eq_(0, OutboxMessage.objects.count())
self.assertEqual(200, resp.status_code)
self.assertEqual(0, OutboxMessage.objects.count())

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.motidings.tests import WatchFactory
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
@ -12,7 +10,7 @@ class UnsubscribeTests(TestCase):
url = reverse("tidings.unsubscribe", args=(watch.id,))
resp = self.client.get(url, follow=True)
eq_(resp.status_code, 200)
self.assertEqual(resp.status_code, 200)
self.assertTemplateUsed("motidings/unsub.html")
def test_view_post_success(self):
@ -21,14 +19,14 @@ class UnsubscribeTests(TestCase):
url = reverse("tidings.unsubscribe", args=(watch.id,), locale="en-US")
resp = self.client.post(url + "?s={0}".format(watch.secret))
eq_(resp.status_code, 200)
self.assertEqual(resp.status_code, 200)
self.assertTemplateUsed("motidings/unsubscribe_success.html")
def test_view_post_error_wrong_doesnotexist(self):
url = reverse("tidings.unsubscribe", args=(42,), locale="en-US")
resp = self.client.post(url + "?s=applesandcinnamon")
eq_(resp.status_code, 200)
self.assertEqual(resp.status_code, 200)
self.assertTemplateUsed("motidings/unsubscribe_error.html")
def test_view_post_error_wrong_secret(self):
@ -36,5 +34,5 @@ class UnsubscribeTests(TestCase):
url = reverse("tidings.unsubscribe", args=(watch.id,), locale="en-US")
resp = self.client.post(url + "?s=applesandcinnamon")
eq_(resp.status_code, 200)
self.assertEqual(resp.status_code, 200)
self.assertTemplateUsed("motidings/unsubscribe_error.html")

Просмотреть файл

@ -1,22 +1,20 @@
from datetime import datetime
from django.contrib.contenttypes.models import ContentType
from unittest.mock import Mock, patch
from actstream.actions import follow
from actstream.signals import action
from actstream.models import Action, Follow
from unittest.mock import Mock, patch
from nose.tools import eq_, ok_
from actstream.signals import action
from django.contrib.contenttypes.models import ContentType
from rest_framework.test import APIClient
from kitsune.notifications import api
from kitsune.notifications import tasks as notification_tasks
from kitsune.notifications.models import Notification, RealtimeRegistration
from kitsune.questions.tests import AnswerFactory, QuestionFactory
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
from kitsune.questions.tests import QuestionFactory, AnswerFactory
from kitsune.users.tests import UserFactory
from kitsune.users.templatetags.jinja_helpers import profile_avatar
from kitsune.users.tests import UserFactory
class TestPushNotificationRegistrationSerializer(TestCase):
@ -38,10 +36,10 @@ class TestPushNotificationRegistrationSerializer(TestCase):
serializer = api.PushNotificationRegistrationSerializer(
context=self.context, data=self.data
)
ok_(serializer.is_valid())
eq_(serializer.errors, {})
assert serializer.is_valid()
self.assertEqual(serializer.errors, {})
obj = serializer.save()
eq_(obj.creator, self.user)
self.assertEqual(obj.creator, self.user)
def test_cant_register_for_other_users(self):
wrong_user = UserFactory()
@ -49,8 +47,8 @@ class TestPushNotificationRegistrationSerializer(TestCase):
serializer = api.PushNotificationRegistrationSerializer(
context=self.context, data=self.data
)
ok_(not serializer.is_valid())
eq_(
assert not serializer.is_valid()
self.assertEqual(
serializer.errors,
{
"creator": ["Can't register push notifications for another user."],
@ -74,8 +72,8 @@ class TestNotificationSerializer(TestCase):
serializer = api.NotificationSerializer(instance=notification)
eq_(serializer.data["is_read"], False)
eq_(
self.assertEqual(serializer.data["is_read"], False)
self.assertEqual(
serializer.data["actor"],
{
"type": "user",
@ -84,10 +82,10 @@ class TestNotificationSerializer(TestCase):
"avatar": profile_avatar(followed),
},
)
eq_(serializer.data["verb"], "asked")
eq_(serializer.data["action_object"]["type"], "question")
eq_(serializer.data["action_object"]["id"], q.id)
eq_(serializer.data["target"], None)
self.assertEqual(serializer.data["verb"], "asked")
self.assertEqual(serializer.data["action_object"]["type"], "question")
self.assertEqual(serializer.data["action_object"]["id"], q.id)
self.assertEqual(serializer.data["target"], None)
# Check that the serialized data is in the correct format. If it is
# not, this will throw an exception.
datetime.strptime(serializer.data["timestamp"], "%Y-%m-%dT%H:%M:%SZ")
@ -118,33 +116,33 @@ class TestNotificationViewSet(TestCase):
n = self._makeNotification()
self.client.force_authenticate(user=self.follower)
res = self.client.post(reverse("notification-mark-read", args=[n.id]))
eq_(res.status_code, 204)
self.assertEqual(res.status_code, 204)
n = Notification.objects.get(id=n.id)
eq_(n.is_read, True)
self.assertEqual(n.is_read, True)
def test_mark_unread(self):
n = self._makeNotification(is_read=True)
self.client.force_authenticate(user=self.follower)
res = self.client.post(reverse("notification-mark-unread", args=[n.id]))
eq_(res.status_code, 204)
self.assertEqual(res.status_code, 204)
n = Notification.objects.get(id=n.id)
eq_(n.is_read, False)
self.assertEqual(n.is_read, False)
def test_filter_is_read_false(self):
n = self._makeNotification(is_read=False)
self._makeNotification(is_read=True)
self.client.force_authenticate(user=self.follower)
res = self.client.get(reverse("notification-list") + "?is_read=0")
eq_(res.status_code, 200)
eq_([d["id"] for d in res.data], [n.id])
self.assertEqual(res.status_code, 200)
self.assertEqual([d["id"] for d in res.data], [n.id])
def test_filter_is_read_true(self):
self._makeNotification(is_read=False)
n = self._makeNotification(is_read=True)
self.client.force_authenticate(user=self.follower)
res = self.client.get(reverse("notification-list") + "?is_read=1")
eq_(res.status_code, 200)
eq_([d["id"] for d in res.data], [n.id])
self.assertEqual(res.status_code, 200)
self.assertEqual([d["id"] for d in res.data], [n.id])
@patch.object(notification_tasks, "requests")
@ -169,13 +167,13 @@ class RealtimeViewSet(TestCase):
self.client.force_authenticate(user=u)
url = reverse("realtimeregistration-updates", args=[rt.id])
res = self.client.get(url)
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)
eq_(len(res.data), 1)
self.assertEqual(len(res.data), 1)
act = res.data[0]
eq_(act["actor"]["username"], a.creator.username)
eq_(act["target"]["content"], q.content_parsed)
eq_(act["action_object"]["content"], a.content_parsed)
self.assertEqual(act["actor"]["username"], a.creator.username)
self.assertEqual(act["target"]["content"], q.content_parsed)
self.assertEqual(act["action_object"]["content"], a.content_parsed)
def test_is_cors(self, requests):
u = UserFactory()
@ -188,5 +186,5 @@ class RealtimeViewSet(TestCase):
"endpoint": "http://example.com",
}
res = self.client.post(url, data, HTTP_ORIGIN="http://example.com")
eq_(res.status_code, 201)
eq_(res["Access-Control-Allow-Origin"], "*")
self.assertEqual(res.status_code, 201)
self.assertEqual(res["Access-Control-Allow-Origin"], "*")

Просмотреть файл

@ -1,7 +1,5 @@
from datetime import datetime
from nose.tools import eq_
from kitsune.notifications.tests import NotificationFactory
from kitsune.sumo.tests import TestCase
@ -9,11 +7,11 @@ from kitsune.sumo.tests import TestCase
class TestNotificationModel(TestCase):
def test_is_read_false(self):
n = NotificationFactory(read_at=None)
eq_(n.is_read, False)
self.assertEqual(n.is_read, False)
def test_is_read_true(self):
n = NotificationFactory(read_at=datetime.now())
eq_(n.is_read, True)
self.assertEqual(n.is_read, True)
def test_set_is_read_true(self):
n = NotificationFactory(read_at=None)

Просмотреть файл

@ -1,10 +1,9 @@
from django.contrib.contenttypes.models import ContentType
from unittest import mock
from actstream.actions import follow
from actstream.signals import action
from actstream.models import Action, Follow
from nose.tools import eq_
from actstream.signals import action
from django.contrib.contenttypes.models import ContentType
from kitsune.notifications import tasks as notification_tasks
from kitsune.notifications.models import (
@ -32,8 +31,8 @@ class TestNotificationsSentFromActions(TestCase):
act = Action.objects.order_by("-id")[0]
notification = Notification.objects.get(action=act)
eq_(notification.owner, follower)
eq_(notification.action, act)
self.assertEqual(notification.owner, follower)
self.assertEqual(notification.action, act)
def test_following_target(self):
follower = UserFactory()
@ -48,8 +47,8 @@ class TestNotificationsSentFromActions(TestCase):
act = Action.objects.order_by("-id")[0]
notification = Notification.objects.get(action=act)
eq_(notification.owner, follower)
eq_(notification.action, act)
self.assertEqual(notification.owner, follower)
self.assertEqual(notification.action, act)
def test_following_action_object(self):
follower = UserFactory()
@ -63,8 +62,8 @@ class TestNotificationsSentFromActions(TestCase):
act = Action.objects.order_by("-id")[0]
notification = Notification.objects.get(action=act)
eq_(notification.owner, follower)
eq_(notification.action, act)
self.assertEqual(notification.owner, follower)
self.assertEqual(notification.action, act)
def test_no_action_for_self(self):
"""Test that a notification is not sent for actions the user took."""
@ -77,7 +76,7 @@ class TestNotificationsSentFromActions(TestCase):
# Make a new action for the above. This should not trigger notifications.
action.send(q.creator, verb="edited", action_object=q)
act = Action.objects.order_by("-id")[0]
eq_(Notification.objects.filter(action=act).count(), 0)
self.assertEqual(Notification.objects.filter(action=act).count(), 0)
@mock.patch.object(notification_tasks, "requests")
@ -111,7 +110,7 @@ class TestSimplePushNotifier(TestCase):
n = NotificationFactory(owner=u)
# The push notification handler should try, and then retry 3 times before giving up.
eq_(
self.assertEqual(
requests.put.call_args_list,
[
((url, "version={}".format(n.id)), {}),

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.postcrash.tests import SignatureFactory
from kitsune.sumo.tests import TestCase
@ -7,4 +5,4 @@ from kitsune.sumo.tests import TestCase
class SignatureTests(TestCase):
def test_get_absolute_url(self):
sig = SignatureFactory(document__slug="foo-bar")
eq_("/kb/foo-bar", sig.get_absolute_url())
self.assertEqual("/kb/foo-bar", sig.get_absolute_url())

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.postcrash.tests import SignatureFactory
from kitsune.sumo.templatetags.jinja_helpers import urlparams
from kitsune.sumo.tests import TestCase
@ -9,21 +7,23 @@ from kitsune.sumo.urlresolvers import reverse
class ApiTests(TestCase):
def test_no_signature(self):
response = self.client.get(reverse("postcrash.api"))
eq_(400, response.status_code)
eq_(b"", response.content)
eq_("text/plain", response["content-type"])
self.assertEqual(400, response.status_code)
self.assertEqual(b"", response.content)
self.assertEqual("text/plain", response["content-type"])
def test_unknown_signature(self):
url = urlparams(reverse("postcrash.api"), s="foo")
response = self.client.get(url)
eq_(404, response.status_code)
eq_(b"", response.content)
eq_("text/plain", response["content-type"])
self.assertEqual(404, response.status_code)
self.assertEqual(b"", response.content)
self.assertEqual("text/plain", response["content-type"])
def test_known_signature(self):
sig = SignatureFactory()
url = urlparams(reverse("postcrash.api"), s=sig.signature)
response = self.client.get(url)
eq_(200, response.status_code)
eq_("https://example.com/kb/%s" % sig.document.slug, response.content.decode())
eq_("text/plain", response["content-type"])
self.assertEqual(200, response.status_code)
self.assertEqual(
"https://example.com/kb/%s" % sig.document.slug, response.content.decode()
)
self.assertEqual("text/plain", response["content-type"])

Просмотреть файл

@ -1,9 +1,7 @@
from nose.tools import eq_
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
from kitsune.products import api
from kitsune.products.tests import ProductFactory, TopicFactory
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
class TestProductSerializerSerialization(TestCase):
@ -11,14 +9,14 @@ class TestProductSerializerSerialization(TestCase):
p = ProductFactory(image=None)
serializer = api.ProductSerializer()
native = serializer.to_representation(p)
eq_(native["image"], None)
self.assertEqual(native["image"], None)
def test_product_with_image_works(self):
# The factory will make a fictional image for the product
p = ProductFactory()
serializer = api.ProductSerializer()
data = serializer.to_representation(p)
eq_(data["image"], p.image.url)
self.assertEqual(data["image"], p.image.url)
class TestTopicListView(TestCase):
@ -26,7 +24,7 @@ class TestTopicListView(TestCase):
p = ProductFactory()
url = reverse("topic-list", kwargs={"product": p.slug})
res = self.client.get(url)
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)
def test_expected_output(self):
p = ProductFactory()
@ -35,9 +33,9 @@ class TestTopicListView(TestCase):
url = reverse("topic-list", kwargs={"product": p.slug})
res = self.client.get(url)
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)
eq_(
self.assertEqual(
res.data,
{
"count": 2,

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.products.tests import ProductFactory, TopicFactory
from kitsune.sumo.tests import TestCase
@ -12,16 +10,16 @@ class TopicModelTests(TestCase):
t2 = TopicFactory(product=p, slug="t2", parent=t1)
t3 = TopicFactory(product=p, slug="t3", parent=t2)
eq_(t1.path, [t1.slug])
eq_(t2.path, [t1.slug, t2.slug])
eq_(t3.path, [t1.slug, t2.slug, t3.slug])
self.assertEqual(t1.path, [t1.slug])
self.assertEqual(t2.path, [t1.slug, t2.slug])
self.assertEqual(t3.path, [t1.slug, t2.slug, t3.slug])
def test_absolute_url(self):
p = ProductFactory()
t = TopicFactory(product=p)
expected = "/products/{p}/{t}".format(p=p.slug, t=t.slug)
actual = t.get_absolute_url()
eq_(actual, expected)
self.assertEqual(actual, expected)
def test_absolute_url_subtopic(self):
p = ProductFactory()
@ -29,7 +27,7 @@ class TopicModelTests(TestCase):
t2 = TopicFactory(parent=t1, product=p)
expected = "/products/{p}/{t1}/{t2}".format(p=p.slug, t1=t1.slug, t2=t2.slug)
actual = t2.get_absolute_url()
eq_(actual, expected)
self.assertEqual(actual, expected)
class ProductModelTests(TestCase):
@ -37,4 +35,4 @@ class ProductModelTests(TestCase):
p = ProductFactory()
expected = "/products/{p}".format(p=p.slug)
actual = p.get_absolute_url()
eq_(actual, expected)
self.assertEqual(actual, expected)

Просмотреть файл

@ -1,6 +1,5 @@
from django.conf import settings
from django.core.cache import cache
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.products.models import HOT_TOPIC_SLUG
@ -24,9 +23,9 @@ class ProductViewsTestCase(Elastic7TestCase):
# GET the products page and verify the content.
r = self.client.get(reverse("products"), follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(3, len(doc("#products-and-services li")))
self.assertEqual(3, len(doc("#products-and-services li")))
def test_product_landing(self):
"""Verify that /products/<slug> page renders topics."""
@ -48,19 +47,19 @@ class ProductViewsTestCase(Elastic7TestCase):
# GET the product landing page and verify the content.
url = reverse("products.product", args=[p.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(11, len(doc("#help-topics li")))
eq_(p.slug, doc("#support-search input[name=product]").attr["value"])
self.assertEqual(11, len(doc("#help-topics li")))
self.assertEqual(p.slug, doc("#support-search input[name=product]").attr["value"])
def test_firefox_product_landing(self):
"""Verify that there are no firefox button at header in the firefox landing page"""
p = ProductFactory(slug="firefox")
url = reverse("products.product", args=[p.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(False, doc(".firefox-download-button").length)
self.assertEqual(False, doc(".firefox-download-button").length)
def test_document_listing(self):
"""Verify /products/<product slug>/<topic slug> renders articles."""
@ -77,10 +76,10 @@ class ProductViewsTestCase(Elastic7TestCase):
# GET the page and verify the content.
url = reverse("products.documents", args=[p.slug, t1.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(3, len(doc("#document-list > ul > li")))
eq_(p.slug, doc("#support-search input[name=product]").attr["value"])
self.assertEqual(3, len(doc("#document-list > ul > li")))
self.assertEqual(p.slug, doc("#support-search input[name=product]").attr["value"])
def test_document_listing_order(self):
"""Verify documents are sorted by display_order and number of helpful votes."""
@ -101,9 +100,9 @@ class ProductViewsTestCase(Elastic7TestCase):
self.refresh()
url = reverse("products.documents", args=[p.slug, t.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(doc("#document-list > ul > li:first-child > a").text(), docs[1].title)
self.assertEqual(doc("#document-list > ul > li:first-child > a").text(), docs[1].title)
# Add a helpful vote to the third document. It should be second now.
rev = docs[2].current_revision
@ -113,9 +112,9 @@ class ProductViewsTestCase(Elastic7TestCase):
cache.clear() # documents_for() is cached
url = reverse("products.documents", args=[p.slug, t.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(doc("#document-list > ul > li:nth-child(2) > a").text(), docs[2].title)
self.assertEqual(doc("#document-list > ul > li:nth-child(2) > a").text(), docs[2].title)
# Add 2 helpful votes the first document. It should be second now.
rev = docs[0].current_revision
@ -125,9 +124,9 @@ class ProductViewsTestCase(Elastic7TestCase):
self.refresh()
cache.clear() # documents_for() is cached
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
doc = pq(r.content)
eq_(doc("#document-list > ul > li:nth-child(2) > a").text(), docs[0].title)
self.assertEqual(doc("#document-list > ul > li:nth-child(2) > a").text(), docs[0].title)
def test_subtopics(self):
"""Verifies subtopics appear on document listing page."""
@ -144,23 +143,23 @@ class ProductViewsTestCase(Elastic7TestCase):
# GET the page and verify no subtopics yet.
url = reverse("products.documents", args=[p.slug, t.slug])
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
pqdoc = pq(r.content)
eq_(0, len(pqdoc("li.subtopic")))
self.assertEqual(0, len(pqdoc("li.subtopic")))
# Create a subtopic, it still shouldn't show up because no
# articles are assigned.
subtopic = TopicFactory(parent=t, product=p, visible=True)
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
pqdoc = pq(r.content)
eq_(0, len(pqdoc("li.subtopic")))
self.assertEqual(0, len(pqdoc("li.subtopic")))
# Add a document to the subtopic, now it should appear.
doc.topics.add(subtopic)
self.refresh()
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
pqdoc = pq(r.content)
eq_(1, len(pqdoc("li.subtopic")))
self.assertEqual(1, len(pqdoc("li.subtopic")))

Просмотреть файл

@ -1,10 +1,9 @@
from datetime import datetime
from nose.tools import eq_
import factory
from kitsune.questions.models import Question, QuestionVote, Answer, AnswerVote, QuestionLocale
from kitsune.sumo.tests import LocalizingClient, TestCase, FuzzyUnicode
from kitsune.questions.models import Answer, AnswerVote, Question, QuestionLocale, QuestionVote
from kitsune.sumo.tests import FuzzyUnicode, LocalizingClient, TestCase
from kitsune.users.tests import UserFactory
@ -16,7 +15,7 @@ class TestCaseBase(TestCase):
def tags_eq(tagged_object, tag_names):
"""Assert that the names of the tags on tagged_object are tag_names."""
eq_(sorted([t.name for t in tagged_object.tags.all()]), sorted(tag_names))
TestCase().assertEqual(sorted([t.name for t in tagged_object.tags.all()]), sorted(tag_names))
class QuestionFactory(factory.django.DjangoModelFactory):

Просмотреть файл

@ -1,29 +1,28 @@
import json
from datetime import datetime, timedelta
from unittest import mock
import actstream.actions
from actstream.models import Follow
from nose.tools import eq_, ok_, raises
from rest_framework.test import APIClient
from rest_framework.exceptions import APIException
from rest_framework.test import APIClient
from taggit.models import Tag
from kitsune.sumo.tests import TestCase
from kitsune.questions import api
from kitsune.questions.models import Question, Answer
from kitsune.questions.tests import (
tags_eq,
QuestionFactory,
AnswerFactory,
QuestionVoteFactory,
AnswerVoteFactory,
)
from kitsune.products.tests import ProductFactory, TopicFactory
from kitsune.questions import api
from kitsune.questions.models import Answer, Question
from kitsune.questions.tests import (
AnswerFactory,
AnswerVoteFactory,
QuestionFactory,
QuestionVoteFactory,
tags_eq,
)
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
from kitsune.tags.tests import TagFactory
from kitsune.users.templatetags.jinja_helpers import profile_avatar
from kitsune.users.models import Profile
from kitsune.users.templatetags.jinja_helpers import profile_avatar
from kitsune.users.tests import UserFactory, add_permission
@ -54,13 +53,13 @@ class TestQuestionSerializerDeserialization(TestCase):
serializer = api.QuestionSerializer(context=self.context, data=self.data)
serializer.is_valid(raise_exception=True)
obj = serializer.save()
eq_(obj.creator, self.user)
self.assertEqual(obj.creator, self.user)
def test_product_required(self):
del self.data["product"]
serializer = api.QuestionSerializer(context=self.context, data=self.data)
ok_(not serializer.is_valid())
eq_(
assert not serializer.is_valid()
self.assertEqual(
serializer.errors,
{
"product": ["This field is required."],
@ -71,8 +70,8 @@ class TestQuestionSerializerDeserialization(TestCase):
def test_topic_required(self):
del self.data["topic"]
serializer = api.QuestionSerializer(context=self.context, data=self.data)
ok_(not serializer.is_valid())
eq_(
assert not serializer.is_valid()
self.assertEqual(
serializer.errors,
{
"topic": ["This field is required."],
@ -87,7 +86,7 @@ class TestQuestionSerializerDeserialization(TestCase):
serializer = api.QuestionSerializer(context=self.context, data=self.data)
serializer.is_valid(raise_exception=True)
obj = serializer.save()
eq_(obj.topic, self.topic)
self.assertEqual(obj.topic, self.topic)
def test_solution_is_readonly(self):
q = QuestionFactory()
@ -96,7 +95,7 @@ class TestQuestionSerializerDeserialization(TestCase):
serializer = api.QuestionSerializer(context=self.context, data=self.data, instance=q)
serializer.is_valid(raise_exception=True)
serializer.save()
eq_(q.solution, None)
self.assertEqual(q.solution, None)
class TestQuestionSerializerSerialization(TestCase):
@ -124,24 +123,24 @@ class TestQuestionSerializerSerialization(TestCase):
def test_no_votes(self):
serializer = api.QuestionSerializer(instance=self.question)
eq_(serializer.data["num_votes"], 0)
self.assertEqual(serializer.data["num_votes"], 0)
def test_with_votes(self):
QuestionVoteFactory(question=self.question)
QuestionVoteFactory(question=self.question)
QuestionVoteFactory()
serializer = api.QuestionSerializer(instance=self.question)
eq_(serializer.data["num_votes"], 2)
self.assertEqual(serializer.data["num_votes"], 2)
def test_just_asker(self):
serializer = api.QuestionSerializer(instance=self.question)
eq_(serializer.data["involved"], self._names(self.asker))
self.assertEqual(serializer.data["involved"], self._names(self.asker))
def test_one_answer(self):
self._answer(self.helper1)
serializer = api.QuestionSerializer(instance=self.question)
eq_(
self.assertEqual(
sorted(serializer.data["involved"], key=lambda d: d["username"]),
self._names(self.asker, self.helper1),
)
@ -151,7 +150,7 @@ class TestQuestionSerializerSerialization(TestCase):
self._answer(self.asker)
serializer = api.QuestionSerializer(instance=self.question)
eq_(
self.assertEqual(
sorted(serializer.data["involved"], key=lambda d: d["username"]),
self._names(self.asker, self.helper1),
)
@ -162,7 +161,7 @@ class TestQuestionSerializerSerialization(TestCase):
self._answer(self.helper2)
serializer = api.QuestionSerializer(instance=self.question)
eq_(
self.assertEqual(
sorted(serializer.data["involved"], key=lambda d: d["username"]),
self._names(self.asker, self.helper1, self.helper2),
)
@ -173,11 +172,11 @@ class TestQuestionSerializerSerialization(TestCase):
self.question.save()
serializer = api.QuestionSerializer(instance=self.question)
eq_(serializer.data["solution"], a.id)
self.assertEqual(serializer.data["solution"], a.id)
def test_creator_is_object(self):
serializer = api.QuestionSerializer(instance=self.question)
eq_(
self.assertEqual(
serializer.data["creator"],
{
"username": self.question.creator.username,
@ -190,7 +189,7 @@ class TestQuestionSerializerSerialization(TestCase):
self.question.tags.add("tag1")
self.question.tags.add("tag2")
serializer = api.QuestionSerializer(instance=self.question)
eq_(
self.assertEqual(
serializer.data["tags"],
[
{"name": "tag1", "slug": "tag1"},
@ -214,14 +213,14 @@ class TestQuestionViewSet(TestCase):
"product": p.slug,
"topic": t.slug,
}
eq_(Question.objects.count(), 0)
self.assertEqual(Question.objects.count(), 0)
res = self.client.post(reverse("question-list"), data)
eq_(res.status_code, 201)
eq_(Question.objects.count(), 1)
self.assertEqual(res.status_code, 201)
self.assertEqual(Question.objects.count(), 1)
q = Question.objects.all()[0]
eq_(q.title, data["title"])
eq_(q.content, data["content"])
eq_(q.content_parsed, res.data["content"])
self.assertEqual(q.title, data["title"])
self.assertEqual(q.content, data["content"])
self.assertEqual(q.content_parsed, res.data["content"])
def test_delete_permissions(self):
u1 = UserFactory()
@ -231,17 +230,17 @@ class TestQuestionViewSet(TestCase):
# Anonymous user can't delete
self.client.force_authenticate(user=None)
res = self.client.delete(reverse("question-detail", args=[q.id]))
eq_(res.status_code, 401) # Unauthorized
self.assertEqual(res.status_code, 401) # Unauthorized
# Non-owner can't delete
self.client.force_authenticate(user=u2)
res = self.client.delete(reverse("question-detail", args=[q.id]))
eq_(res.status_code, 403) # Forbidden
self.assertEqual(res.status_code, 403) # Forbidden
# Owner can delete
self.client.force_authenticate(user=u1)
res = self.client.delete(reverse("question-detail", args=[q.id]))
eq_(res.status_code, 204) # No content
self.assertEqual(res.status_code, 204) # No content
def test_solve(self):
q = QuestionFactory()
@ -249,9 +248,9 @@ class TestQuestionViewSet(TestCase):
self.client.force_authenticate(user=q.creator)
res = self.client.post(reverse("question-solve", args=[q.id]), data={"answer": a.id})
eq_(res.status_code, 204)
self.assertEqual(res.status_code, 204)
q = Question.objects.get(id=q.id)
eq_(q.solution, a)
self.assertEqual(q.solution, a)
def test_filter_is_taken_true(self):
q1 = QuestionFactory()
@ -261,9 +260,9 @@ class TestQuestionViewSet(TestCase):
url = reverse("question-list") + "?is_taken=1"
res = self.client.get(url)
eq_(res.status_code, 200)
eq_(res.data["count"], 1)
eq_(res.data["results"][0]["id"], q2.id)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data["count"], 1)
self.assertEqual(res.data["results"][0]["id"], q2.id)
def test_filter_is_taken_false(self):
q1 = QuestionFactory()
@ -273,9 +272,9 @@ class TestQuestionViewSet(TestCase):
url = reverse("question-list") + "?is_taken=0"
res = self.client.get(url)
eq_(res.status_code, 200)
eq_(res.data["count"], 1)
eq_(res.data["results"][0]["id"], q1.id)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data["count"], 1)
self.assertEqual(res.data["results"][0]["id"], q1.id)
def test_filter_is_taken_expired(self):
q = QuestionFactory()
@ -286,8 +285,8 @@ class TestQuestionViewSet(TestCase):
url = reverse("question-list") + "?is_taken=1"
res = self.client.get(url)
eq_(res.status_code, 200)
eq_(res.data["count"], 0)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data["count"], 0)
def test_filter_taken_by_username(self):
q1 = QuestionFactory()
@ -297,18 +296,18 @@ class TestQuestionViewSet(TestCase):
url = reverse("question-list") + "?taken_by=" + q1.creator.username
res = self.client.get(url)
eq_(res.status_code, 200)
eq_(res.data["count"], 1)
eq_(res.data["results"][0]["id"], q2.id)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data["count"], 1)
self.assertEqual(res.data["results"][0]["id"], q2.id)
def test_helpful(self):
q = QuestionFactory()
u = UserFactory()
self.client.force_authenticate(user=u)
res = self.client.post(reverse("question-helpful", args=[q.id]))
eq_(res.status_code, 200)
eq_(res.data, {"num_votes": 1})
eq_(Question.objects.get(id=q.id).num_votes, 1)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data, {"num_votes": 1})
self.assertEqual(Question.objects.get(id=q.id).num_votes, 1)
def test_helpful_double_vote(self):
q = QuestionFactory()
@ -316,34 +315,34 @@ class TestQuestionViewSet(TestCase):
QuestionVoteFactory(question=q, creator=u)
self.client.force_authenticate(user=u)
res = self.client.post(reverse("question-helpful", args=[q.id]))
eq_(res.status_code, 409)
self.assertEqual(res.status_code, 409)
# It's 1, not 0, because one was created above. The failure cause is
# if the number of votes is 2, one from above and one from the api call.
eq_(Question.objects.get(id=q.id).num_votes, 1)
self.assertEqual(Question.objects.get(id=q.id).num_votes, 1)
def test_helpful_question_not_editable(self):
q = QuestionFactory(is_locked=True)
u = UserFactory()
self.client.force_authenticate(user=u)
res = self.client.post(reverse("question-helpful", args=[q.id]))
eq_(res.status_code, 403)
eq_(Question.objects.get(id=q.id).num_votes, 0)
self.assertEqual(res.status_code, 403)
self.assertEqual(Question.objects.get(id=q.id).num_votes, 0)
def test_ordering(self):
q1 = QuestionFactory()
q2 = QuestionFactory()
res = self.client.get(reverse("question-list"))
eq_(res.data["results"][0]["id"], q2.id)
eq_(res.data["results"][1]["id"], q1.id)
self.assertEqual(res.data["results"][0]["id"], q2.id)
self.assertEqual(res.data["results"][1]["id"], q1.id)
res = self.client.get(reverse("question-list") + "?ordering=id")
eq_(res.data["results"][0]["id"], q1.id)
eq_(res.data["results"][1]["id"], q2.id)
self.assertEqual(res.data["results"][0]["id"], q1.id)
self.assertEqual(res.data["results"][1]["id"], q2.id)
res = self.client.get(reverse("question-list") + "?ordering=-id")
eq_(res.data["results"][0]["id"], q2.id)
eq_(res.data["results"][1]["id"], q1.id)
self.assertEqual(res.data["results"][0]["id"], q2.id)
self.assertEqual(res.data["results"][1]["id"], q1.id)
def test_filter_product_with_slug(self):
p1 = ProductFactory()
@ -353,8 +352,8 @@ class TestQuestionViewSet(TestCase):
querystring = "?product={0}".format(p1.slug)
res = self.client.get(reverse("question-list") + querystring)
eq_(len(res.data["results"]), 1)
eq_(res.data["results"][0]["id"], q1.id)
self.assertEqual(len(res.data["results"]), 1)
self.assertEqual(res.data["results"][0]["id"], q1.id)
def test_filter_creator_with_username(self):
q1 = QuestionFactory()
@ -362,9 +361,9 @@ class TestQuestionViewSet(TestCase):
querystring = "?creator={0}".format(q1.creator.username)
res = self.client.get(reverse("question-list") + querystring)
eq_(res.status_code, 200)
eq_(len(res.data["results"]), 1)
eq_(res.data["results"][0]["id"], q1.id)
self.assertEqual(res.status_code, 200)
self.assertEqual(len(res.data["results"]), 1)
self.assertEqual(res.data["results"][0]["id"], q1.id)
def test_filter_involved(self):
q1 = QuestionFactory()
@ -373,17 +372,17 @@ class TestQuestionViewSet(TestCase):
querystring = "?involved={0}".format(q1.creator.username)
res = self.client.get(reverse("question-list") + querystring)
eq_(res.status_code, 200)
eq_(len(res.data["results"]), 1)
eq_(res.data["results"][0]["id"], q1.id)
self.assertEqual(res.status_code, 200)
self.assertEqual(len(res.data["results"]), 1)
self.assertEqual(res.data["results"][0]["id"], q1.id)
querystring = "?involved={0}".format(q2.creator.username)
res = self.client.get(reverse("question-list") + querystring)
eq_(res.status_code, 200)
eq_(len(res.data["results"]), 2)
self.assertEqual(res.status_code, 200)
self.assertEqual(len(res.data["results"]), 2)
# The API has a default sort, so ordering will be consistent.
eq_(res.data["results"][0]["id"], q2.id)
eq_(res.data["results"][1]["id"], q1.id)
self.assertEqual(res.data["results"][0]["id"], q2.id)
self.assertEqual(res.data["results"][1]["id"], q1.id)
def test_is_taken(self):
q = QuestionFactory()
@ -391,25 +390,25 @@ class TestQuestionViewSet(TestCase):
q.take(u)
url = reverse("question-detail", args=[q.id])
res = self.client.get(url)
eq_(res.status_code, 200)
eq_(res.data["taken_by"]["username"], u.username)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data["taken_by"]["username"], u.username)
def test_take(self):
q = QuestionFactory()
u = UserFactory()
self.client.force_authenticate(user=u)
res = self.client.post(reverse("question-take", args=[q.id]))
eq_(res.status_code, 204)
self.assertEqual(res.status_code, 204)
q = Question.objects.get(id=q.id)
eq_(q.taken_by, u)
self.assertEqual(q.taken_by, u)
def test_take_by_owner(self):
q = QuestionFactory()
self.client.force_authenticate(user=q.creator)
res = self.client.post(reverse("question-take", args=[q.id]))
eq_(res.status_code, 400)
self.assertEqual(res.status_code, 400)
q = Question.objects.get(id=q.id)
eq_(q.taken_by, None)
self.assertEqual(q.taken_by, None)
def test_take_conflict(self):
u1 = UserFactory()
@ -418,33 +417,33 @@ class TestQuestionViewSet(TestCase):
q = QuestionFactory(taken_until=taken_until, taken_by=u1)
self.client.force_authenticate(user=u2)
res = self.client.post(reverse("question-take", args=[q.id]))
eq_(res.status_code, 409)
self.assertEqual(res.status_code, 409)
q = Question.objects.get(id=q.id)
eq_(q.taken_by, u1)
self.assertEqual(q.taken_by, u1)
def test_follow(self):
q = QuestionFactory()
u = UserFactory()
self.client.force_authenticate(user=u)
res = self.client.post(reverse("question-follow", args=[q.id]))
eq_(res.status_code, 204)
self.assertEqual(res.status_code, 204)
f = Follow.objects.get(user=u)
eq_(f.follow_object, q)
eq_(f.actor_only, False)
self.assertEqual(f.follow_object, q)
self.assertEqual(f.actor_only, False)
def test_unfollow(self):
q = QuestionFactory()
u = UserFactory()
actstream.actions.follow(u, q, actor_only=False)
eq_(Follow.objects.filter(user=u).count(), 1) # pre-condition
self.assertEqual(Follow.objects.filter(user=u).count(), 1) # pre-condition
self.client.force_authenticate(user=u)
res = self.client.post(reverse("question-unfollow", args=[q.id]))
eq_(res.status_code, 204)
eq_(Follow.objects.filter(user=u).count(), 0)
self.assertEqual(res.status_code, 204)
self.assertEqual(Follow.objects.filter(user=u).count(), 0)
def test_add_tags(self):
q = QuestionFactory()
eq_(0, q.tags.count())
self.assertEqual(0, q.tags.count())
u = UserFactory()
add_permission(u, Tag, "add_tag")
@ -455,15 +454,15 @@ class TestQuestionViewSet(TestCase):
content_type="application/json",
data=json.dumps({"tags": ["test", "more", "tags"]}),
)
eq_(res.status_code, 200)
eq_(3, q.tags.count())
self.assertEqual(res.status_code, 200)
self.assertEqual(3, q.tags.count())
def test_remove_tags(self):
q = QuestionFactory()
q.tags.add("test")
q.tags.add("more")
q.tags.add("tags")
eq_(3, q.tags.count())
self.assertEqual(3, q.tags.count())
u = UserFactory()
self.client.force_authenticate(user=u)
@ -473,15 +472,15 @@ class TestQuestionViewSet(TestCase):
content_type="application/json",
data=json.dumps({"tags": ["more", "tags"]}),
)
eq_(res.status_code, 204)
eq_(1, q.tags.count())
self.assertEqual(res.status_code, 204)
self.assertEqual(1, q.tags.count())
def test_bleaching(self):
"""Tests whether question content is bleached."""
q = QuestionFactory(content="<unbleached>Cupcakes are the best</unbleached>")
url = reverse("question-detail", args=[q.id])
res = self.client.get(url)
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)
assert "<unbleached>" not in res.data["content"]
def test_auto_tagging(self):
@ -496,13 +495,13 @@ class TestQuestionViewSet(TestCase):
content_type="application/json",
data=json.dumps({"name": "product", "value": "desktop"}),
)
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)
tags_eq(q, [])
res = self.client.post(
reverse("question-auto-tag", args=[q.id]), content_type="application/json"
)
eq_(res.status_code, 204)
self.assertEqual(res.status_code, 204)
tags_eq(q, ["desktop"])
@ -510,8 +509,8 @@ class TestAnswerSerializerDeserialization(TestCase):
def test_no_votes(self):
a = AnswerFactory()
serializer = api.AnswerSerializer(instance=a)
eq_(serializer.data["num_helpful_votes"], 0)
eq_(serializer.data["num_unhelpful_votes"], 0)
self.assertEqual(serializer.data["num_helpful_votes"], 0)
self.assertEqual(serializer.data["num_unhelpful_votes"], 0)
def test_with_votes(self):
a = AnswerFactory()
@ -521,8 +520,8 @@ class TestAnswerSerializerDeserialization(TestCase):
AnswerVoteFactory()
serializer = api.AnswerSerializer(instance=a)
eq_(serializer.data["num_helpful_votes"], 2)
eq_(serializer.data["num_unhelpful_votes"], 1)
self.assertEqual(serializer.data["num_helpful_votes"], 2)
self.assertEqual(serializer.data["num_unhelpful_votes"], 1)
class TestAnswerViewSet(TestCase):
@ -537,14 +536,14 @@ class TestAnswerViewSet(TestCase):
"question": q.id,
"content": "You just need to click the fox.",
}
eq_(Answer.objects.count(), 0)
self.assertEqual(Answer.objects.count(), 0)
res = self.client.post(reverse("answer-list"), data)
eq_(res.status_code, 201)
eq_(Answer.objects.count(), 1)
self.assertEqual(res.status_code, 201)
self.assertEqual(Answer.objects.count(), 1)
a = Answer.objects.all()[0]
eq_(a.content, data["content"])
eq_(a.content_parsed, res.data["content"])
eq_(a.question, q)
self.assertEqual(a.content, data["content"])
self.assertEqual(a.content_parsed, res.data["content"])
self.assertEqual(a.question, q)
def test_delete_permissions(self):
u1 = UserFactory()
@ -554,42 +553,42 @@ class TestAnswerViewSet(TestCase):
# Anonymous user can't delete
self.client.force_authenticate(user=None)
res = self.client.delete(reverse("answer-detail", args=[a.id]))
eq_(res.status_code, 401) # Unauthorized
self.assertEqual(res.status_code, 401) # Unauthorized
# Non-owner can't deletea
self.client.force_authenticate(user=u2)
res = self.client.delete(reverse("answer-detail", args=[a.id]))
eq_(res.status_code, 403) # Forbidden
self.assertEqual(res.status_code, 403) # Forbidden
# Owner can delete
self.client.force_authenticate(user=u1)
res = self.client.delete(reverse("answer-detail", args=[a.id]))
eq_(res.status_code, 204) # No content
self.assertEqual(res.status_code, 204) # No content
def test_ordering(self):
a1 = AnswerFactory()
a2 = AnswerFactory()
res = self.client.get(reverse("answer-list"))
eq_(res.data["results"][0]["id"], a2.id)
eq_(res.data["results"][1]["id"], a1.id)
self.assertEqual(res.data["results"][0]["id"], a2.id)
self.assertEqual(res.data["results"][1]["id"], a1.id)
res = self.client.get(reverse("answer-list") + "?ordering=id")
eq_(res.data["results"][0]["id"], a1.id)
eq_(res.data["results"][1]["id"], a2.id)
self.assertEqual(res.data["results"][0]["id"], a1.id)
self.assertEqual(res.data["results"][1]["id"], a2.id)
res = self.client.get(reverse("answer-list") + "?ordering=-id")
eq_(res.data["results"][0]["id"], a2.id)
eq_(res.data["results"][1]["id"], a1.id)
self.assertEqual(res.data["results"][0]["id"], a2.id)
self.assertEqual(res.data["results"][1]["id"], a1.id)
def test_helpful(self):
a = AnswerFactory()
u = UserFactory()
self.client.force_authenticate(user=u)
res = self.client.post(reverse("answer-helpful", args=[a.id]))
eq_(res.status_code, 200)
eq_(res.data, {"num_helpful_votes": 1, "num_unhelpful_votes": 0})
eq_(Answer.objects.get(id=a.id).num_votes, 1)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data, {"num_helpful_votes": 1, "num_unhelpful_votes": 0})
self.assertEqual(Answer.objects.get(id=a.id).num_votes, 1)
def test_helpful_double_vote(self):
a = AnswerFactory()
@ -597,10 +596,10 @@ class TestAnswerViewSet(TestCase):
AnswerVoteFactory(answer=a, creator=u)
self.client.force_authenticate(user=u)
res = self.client.post(reverse("answer-helpful", args=[a.id]))
eq_(res.status_code, 409)
self.assertEqual(res.status_code, 409)
# It's 1, not 0, because one was created above. The failure cause is
# if the number of votes is 2, one from above and one from the api call.
eq_(Answer.objects.get(id=a.id).num_votes, 1)
self.assertEqual(Answer.objects.get(id=a.id).num_votes, 1)
def test_helpful_answer_not_editable(self):
q = QuestionFactory(is_locked=True)
@ -608,36 +607,36 @@ class TestAnswerViewSet(TestCase):
u = UserFactory()
self.client.force_authenticate(user=u)
res = self.client.post(reverse("answer-helpful", args=[a.id]))
eq_(res.status_code, 403)
eq_(Answer.objects.get(id=a.id).num_votes, 0)
self.assertEqual(res.status_code, 403)
self.assertEqual(Answer.objects.get(id=a.id).num_votes, 0)
def test_follow(self):
a = AnswerFactory()
u = UserFactory()
self.client.force_authenticate(user=u)
eq_(Follow.objects.filter(user=u).count(), 0) # pre-condition
self.assertEqual(Follow.objects.filter(user=u).count(), 0) # pre-condition
res = self.client.post(reverse("answer-follow", args=[a.id]))
eq_(res.status_code, 204)
self.assertEqual(res.status_code, 204)
f = Follow.objects.get(user=u)
eq_(f.follow_object, a)
eq_(f.actor_only, False)
self.assertEqual(f.follow_object, a)
self.assertEqual(f.actor_only, False)
def test_unfollow(self):
a = AnswerFactory()
u = UserFactory()
actstream.actions.follow(u, a, actor_only=False)
eq_(Follow.objects.filter(user=u).count(), 1) # pre-condition
self.assertEqual(Follow.objects.filter(user=u).count(), 1) # pre-condition
self.client.force_authenticate(user=u)
res = self.client.post(reverse("answer-unfollow", args=[a.id]))
eq_(res.status_code, 204)
eq_(Follow.objects.filter(user=u).count(), 0)
self.assertEqual(res.status_code, 204)
self.assertEqual(Follow.objects.filter(user=u).count(), 0)
def test_bleaching(self):
"""Tests whether answer content is bleached."""
a = AnswerFactory(content="<unbleached>Cupcakes are the best</unbleached>")
url = reverse("answer-detail", args=[a.id])
res = self.client.get(url)
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)
assert "<unbleached>" not in res.data["content"]
@ -659,14 +658,14 @@ class TestQuestionFilter(TestCase):
qs = self.filter_instance.filter_involved(
self.queryset, "filter_involved", q1.creator.username
)
eq_(list(qs), [q1])
self.assertEqual(list(qs), [q1])
qs = self.filter_instance.filter_involved(
self.queryset, "filter_involved", q2.creator.username
)
# The filter does not have a strong order.
qs = sorted(qs, key=lambda q: q.id)
eq_(qs, [q1, q2])
self.assertEqual(qs, [q1, q2])
def test_filter_is_solved(self):
q1 = QuestionFactory()
@ -676,10 +675,10 @@ class TestQuestionFilter(TestCase):
q2 = QuestionFactory()
qs = self.filter_instance.filter_is_solved(self.queryset, "is_solved", True)
eq_(list(qs), [q1])
self.assertEqual(list(qs), [q1])
qs = self.filter_instance.filter_is_solved(self.queryset, "is_solved", False)
eq_(list(qs), [q2])
self.assertEqual(list(qs), [q2])
def test_filter_solved_by(self):
q1 = QuestionFactory()
@ -694,56 +693,56 @@ class TestQuestionFilter(TestCase):
q3.save()
qs = self.filter_instance.filter_solved_by(self.queryset, "solved_by", a1.creator.username)
eq_(list(qs), [q1])
self.assertEqual(list(qs), [q1])
qs = self.filter_instance.filter_solved_by(self.queryset, "solved_by", a3.creator.username)
eq_(list(qs), [q3])
self.assertEqual(list(qs), [q3])
@raises(APIException)
def test_metadata_not_json(self):
self.filter_instance.filter_metadata(self.queryset, "metadata", "not json")
with self.assertRaises(APIException):
self.filter_instance.filter_metadata(self.queryset, "metadata", "not json")
@raises(APIException)
def test_metadata_bad_json(self):
self.filter_instance.filter_metadata(self.queryset, "metadata", "not json")
with self.assertRaises(APIException):
self.filter_instance.filter_metadata(self.queryset, "metadata", "not json")
def test_single_filter_match(self):
q1 = QuestionFactory(metadata={"os": "Linux"})
QuestionFactory(metadata={"os": "OSX"})
res = self.filter({"os": "Linux"})
eq_(list(res), [q1])
self.assertEqual(list(res), [q1])
def test_single_filter_no_match(self):
QuestionFactory(metadata={"os": "Linux"})
QuestionFactory(metadata={"os": "OSX"})
res = self.filter({"os": "Windows 8"})
eq_(list(res), [])
self.assertEqual(list(res), [])
def test_multi_filter_is_and(self):
q1 = QuestionFactory(metadata={"os": "Linux", "category": "troubleshooting"})
QuestionFactory(metadata={"os": "OSX", "category": "troubleshooting"})
res = self.filter({"os": "Linux", "category": "troubleshooting"})
eq_(list(res), [q1])
self.assertEqual(list(res), [q1])
def test_list_value_is_or(self):
q1 = QuestionFactory(metadata={"os": "Linux"})
q2 = QuestionFactory(metadata={"os": "OSX"})
QuestionFactory(metadata={"os": "Windows 7"})
res = self.filter({"os": ["Linux", "OSX"]})
eq_(sorted(res, key=lambda q: q.id), [q1, q2])
self.assertEqual(sorted(res, key=lambda q: q.id), [q1, q2])
def test_none_value_is_missing(self):
q1 = QuestionFactory(metadata={})
QuestionFactory(metadata={"os": "Linux"})
res = self.filter({"os": None})
eq_(list(res), [q1])
self.assertEqual(list(res), [q1])
def test_list_value_with_none(self):
q1 = QuestionFactory(metadata={"os": "Linux"})
q2 = QuestionFactory(metadata={})
QuestionFactory(metadata={"os": "Windows 7"})
res = self.filter({"os": ["Linux", None]})
eq_(sorted(res, key=lambda q: q.id), [q1, q2])
self.assertEqual(sorted(res, key=lambda q: q.id), [q1, q2])
def test_is_taken(self):
u = UserFactory()
@ -751,7 +750,7 @@ class TestQuestionFilter(TestCase):
q = QuestionFactory(taken_by=u, taken_until=taken_until)
QuestionFactory()
res = self.filter_instance.filter_is_taken(self.queryset, "is_taken", True)
eq_(list(res), [q])
self.assertEqual(list(res), [q])
def test_is_not_taken(self):
u = UserFactory()
@ -759,21 +758,21 @@ class TestQuestionFilter(TestCase):
QuestionFactory(taken_by=u, taken_until=taken_until)
q = QuestionFactory()
res = self.filter_instance.filter_is_taken(self.queryset, "is_taken", False)
eq_(list(res), [q])
self.assertEqual(list(res), [q])
def test_is_taken_expired(self):
u = UserFactory()
taken_until = datetime.now() - timedelta(seconds=30)
QuestionFactory(taken_by=u, taken_until=taken_until)
res = self.filter_instance.filter_is_taken(self.queryset, "is_taken", True)
eq_(list(res), [])
self.assertEqual(list(res), [])
def test_is_not_taken_expired(self):
u = UserFactory()
taken_until = datetime.now() - timedelta(seconds=30)
q = QuestionFactory(taken_by=u, taken_until=taken_until)
res = self.filter_instance.filter_is_taken(self.queryset, "is_taken", False)
eq_(list(res), [q])
self.assertEqual(list(res), [q])
def test_it_works_with_users_who_have_gotten_first_contrib_emails(self):
# This flag caused a regression, tracked in bug 1163855.
@ -783,4 +782,4 @@ class TestQuestionFilter(TestCase):
QuestionFactory(creator=u)
url = reverse("question-list")
res = self.client.get(url)
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)

Просмотреть файл

@ -3,7 +3,6 @@ from datetime import datetime, timedelta
from django.contrib.auth.models import Group
from django.core import mail
from django.core.management import call_command
from nose.tools import eq_
from kitsune.questions.tests import AnswerFactory, QuestionFactory
from kitsune.sumo.tests import TestCase
@ -51,4 +50,4 @@ class TestEmployeeReportCron(TestCase):
assert "Number of questions answered: 2" in email.body
assert "{username}: 1".format(username=tracked_user.username) in email.body
eq_([report_user.email], email.to)
self.assertEqual([report_user.email], email.to)

Просмотреть файл

@ -1,16 +1,14 @@
from datetime import datetime, timedelta
from django.core.cache import cache
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.sumo.urlresolvers import reverse
from kitsune.sumo.templatetags.jinja_helpers import urlparams
from kitsune.products.tests import ProductFactory, TopicFactory
from kitsune.questions.feeds import QuestionsFeed, TaggedQuestionsFeed
from kitsune.questions.models import Question
from kitsune.questions.tests import TestCaseBase, QuestionFactory
from kitsune.questions.tests import QuestionFactory, TestCaseBase
from kitsune.sumo.templatetags.jinja_helpers import urlparams
from kitsune.sumo.urlresolvers import reverse
from kitsune.tags.tests import TagFactory
from kitsune.users.tests import UserFactory
@ -22,8 +20,8 @@ class ForumTestFeeds(TestCaseBase):
q = QuestionFactory()
q.tags.add("green")
items = TaggedQuestionsFeed().items(t)
eq_(1, len(items))
eq_(q.id, items[0].id)
self.assertEqual(1, len(items))
self.assertEqual(q.id, items[0].id)
cache.clear()
@ -32,22 +30,22 @@ class ForumTestFeeds(TestCaseBase):
q.updated = datetime.now() + timedelta(days=1)
q.save()
items = TaggedQuestionsFeed().items(t)
eq_(2, len(items))
eq_(q.id, items[0].id)
self.assertEqual(2, len(items))
self.assertEqual(q.id, items[0].id)
def test_tagged_feed_link(self):
"""Make sure the tagged feed is discoverable on the questions page."""
TagFactory(name="green", slug="green")
url = urlparams(reverse("questions.list", args=["all"]), tagged="green")
response = self.client.get(url)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
feed_links = doc('link[type="application/atom+xml"]')
eq_(2, len(feed_links))
eq_("Recently updated questions", feed_links[0].attrib["title"])
eq_("/en-US/questions/feed?product=all", feed_links[0].attrib["href"])
eq_("Recently updated questions tagged green", feed_links[1].attrib["title"])
eq_("/en-US/questions/tagged/green/feed", feed_links[1].attrib["href"])
self.assertEqual(2, len(feed_links))
self.assertEqual("Recently updated questions", feed_links[0].attrib["title"])
self.assertEqual("/en-US/questions/feed?product=all", feed_links[0].attrib["href"])
self.assertEqual("Recently updated questions tagged green", feed_links[1].attrib["title"])
self.assertEqual("/en-US/questions/tagged/green/feed", feed_links[1].attrib["href"])
def test_no_inactive_users(self):
"""Ensure that inactive users' questions don't appear in the feed."""
@ -62,15 +60,15 @@ class ForumTestFeeds(TestCaseBase):
p = ProductFactory()
url = reverse("questions.list", args=[p.slug])
res = self.client.get(url)
eq_(200, res.status_code)
self.assertEqual(200, res.status_code)
doc = pq(res.content)
feed_links = doc('link[type="application/atom+xml"]')
feed = feed_links[0]
eq_(1, len(feed_links))
eq_("Recently updated questions", feed.attrib["title"])
eq_("/en-US/questions/feed?product=" + p.slug, feed.attrib["href"])
eq_(200, self.client.get(feed.attrib["href"]).status_code)
self.assertEqual(1, len(feed_links))
self.assertEqual("Recently updated questions", feed.attrib["title"])
self.assertEqual("/en-US/questions/feed?product=" + p.slug, feed.attrib["href"])
self.assertEqual(200, self.client.get(feed.attrib["href"]).status_code)
def test_question_feed_with_product_and_topic(self):
"""Test that questions feeds with products and topics work."""
@ -78,26 +76,28 @@ class ForumTestFeeds(TestCaseBase):
t = TopicFactory(product=p)
url = urlparams(reverse("questions.list", args=[p.slug]), topic=t.slug)
res = self.client.get(url)
eq_(200, res.status_code)
self.assertEqual(200, res.status_code)
doc = pq(res.content)
feed_links = doc('link[type="application/atom+xml"]')
feed = feed_links[0]
eq_(1, len(feed_links))
eq_("Recently updated questions", feed.attrib["title"])
eq_(urlparams("/en-US/questions/feed", product=p.slug, topic=t.slug), feed.attrib["href"])
eq_(200, self.client.get(feed.attrib["href"]).status_code)
self.assertEqual(1, len(feed_links))
self.assertEqual("Recently updated questions", feed.attrib["title"])
self.assertEqual(
urlparams("/en-US/questions/feed", product=p.slug, topic=t.slug), feed.attrib["href"]
)
self.assertEqual(200, self.client.get(feed.attrib["href"]).status_code)
def test_question_feed_with_locale(self):
"""Test that questions feeds with products and topics work."""
url = reverse("questions.list", args=["all"], locale="pt-BR")
res = self.client.get(url)
eq_(200, res.status_code)
self.assertEqual(200, res.status_code)
doc = pq(res.content)
feed_links = doc('link[type="application/atom+xml"]')
feed = feed_links[0]
eq_(1, len(feed_links))
eq_("Recently updated questions", feed.attrib["title"])
eq_(urlparams("/pt-BR/questions/feed?product=all"), feed.attrib["href"])
eq_(200, self.client.get(feed.attrib["href"]).status_code)
self.assertEqual(1, len(feed_links))
self.assertEqual("Recently updated questions", feed.attrib["title"])
self.assertEqual(urlparams("/pt-BR/questions/feed?product=all"), feed.attrib["href"])
self.assertEqual(200, self.client.get(feed.attrib["href"]).status_code)

Просмотреть файл

@ -1,10 +1,10 @@
from collections import OrderedDict
from django.contrib.auth.models import AnonymousUser
from kitsune.questions.forms import NewQuestionForm, WatchQuestionForm
from kitsune.questions.tests import TestCaseBase
from kitsune.users.tests import UserFactory
from nose.tools import eq_
class WatchQuestionFormTests(TestCaseBase):
@ -15,12 +15,12 @@ class WatchQuestionFormTests(TestCaseBase):
AnonymousUser(), data={"email": "wo@ot.com", "event_type": "reply"}
)
assert form.is_valid()
eq_("wo@ot.com", form.cleaned_data["email"])
self.assertEqual("wo@ot.com", form.cleaned_data["email"])
def test_anonymous_watch_without_email(self):
form = WatchQuestionForm(AnonymousUser(), data={"event_type": "reply"})
assert not form.is_valid()
eq_("Please provide an email.", form.errors["email"][0])
self.assertEqual("Please provide an email.", form.errors["email"][0])
def test_registered_watch_with_email(self):
form = WatchQuestionForm(UserFactory(), data={"email": "wo@ot.com", "event_type": "reply"})
@ -44,7 +44,7 @@ class TestNewQuestionForm(TestCaseBase):
form = NewQuestionForm()
expected = ["category", "useragent"]
actual = form.metadata_field_keys
eq_(expected, actual)
self.assertEqual(expected, actual)
# Test the form with a product
product = {
@ -67,7 +67,7 @@ class TestNewQuestionForm(TestCaseBase):
form = NewQuestionForm(product=product)
expected = ["troubleshooting", "ff_version", "os", "plugins", "useragent", "category"]
actual = form.metadata_field_keys
eq_(sorted(expected), sorted(actual))
self.assertEqual(sorted(expected), sorted(actual))
def test_cleaned_metadata(self):
"""Test the cleaned_metadata property."""
@ -94,7 +94,7 @@ class TestNewQuestionForm(TestCaseBase):
form.is_valid()
expected = {}
actual = form.cleaned_metadata
eq_(expected, actual)
self.assertEqual(expected, actual)
# Test with metadata
data["os"] = "Linux"
@ -102,7 +102,7 @@ class TestNewQuestionForm(TestCaseBase):
form.is_valid()
expected = {"os": "Linux"}
actual = form.cleaned_metadata
eq_(expected, actual)
self.assertEqual(expected, actual)
# Add an empty metadata value
data["ff_version"] = ""
@ -110,4 +110,4 @@ class TestNewQuestionForm(TestCaseBase):
form.is_valid()
expected = {"os": "Linux"}
actual = form.cleaned_metadata
eq_(expected, actual)
self.assertEqual(expected, actual)

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.questions.models import Answer, Question
from kitsune.questions.tests import AnswerFactory, QuestionFactory
from kitsune.sumo.tests import TestCase
@ -10,89 +8,89 @@ class QuestionManagerTestCase(TestCase):
"""Verify the done queryset."""
# Create a question, there shouldn't be any done yet.
q = QuestionFactory()
eq_(0, Question.objects.done().count())
self.assertEqual(0, Question.objects.done().count())
# Add an answer, there shouldn't be any done yet.
a = AnswerFactory(question=q)
eq_(0, Question.objects.done().count())
self.assertEqual(0, Question.objects.done().count())
# Make it the solution, there should be one done.
q.solution = a
q.save()
eq_(1, Question.objects.done().count())
self.assertEqual(1, Question.objects.done().count())
# Create a locked questions, there should be two done.
QuestionFactory(is_locked=True)
eq_(2, Question.objects.done().count())
self.assertEqual(2, Question.objects.done().count())
def test_responded(self):
"""Verify the responded queryset."""
# Create a question, there shouldn't be any responded yet.
q = QuestionFactory()
eq_(0, Question.objects.responded().count())
self.assertEqual(0, Question.objects.responded().count())
# Add an answer, there should be one responded.
a = AnswerFactory(question=q)
eq_(1, Question.objects.responded().count())
self.assertEqual(1, Question.objects.responded().count())
# Add an answer by the creator, there should be none responded.
a = AnswerFactory(creator=q.creator, question=q)
eq_(0, Question.objects.responded().count())
self.assertEqual(0, Question.objects.responded().count())
# Add another answer, there should be one responded.
a = AnswerFactory(question=q)
eq_(1, Question.objects.responded().count())
self.assertEqual(1, Question.objects.responded().count())
# Lock it, there should be none responded.
q.is_locked = True
q.save()
eq_(0, Question.objects.responded().count())
self.assertEqual(0, Question.objects.responded().count())
# Unlock it and mark solved, there should be none responded.
q.is_locked = False
q.solution = a
q.save()
eq_(0, Question.objects.responded().count())
self.assertEqual(0, Question.objects.responded().count())
def test_needs_attention(self):
"""Verify the needs_attention queryset."""
# Create a question, there shouldn't be one needs_attention.
q = QuestionFactory()
eq_(1, Question.objects.needs_attention().count())
self.assertEqual(1, Question.objects.needs_attention().count())
# Add an answer, there should be no needs_attention.
a = AnswerFactory(question=q)
eq_(0, Question.objects.needs_attention().count())
self.assertEqual(0, Question.objects.needs_attention().count())
# Add an answer by the creator, there should be one needs_attention.
a = AnswerFactory(creator=q.creator, question=q)
eq_(1, Question.objects.needs_attention().count())
self.assertEqual(1, Question.objects.needs_attention().count())
# Lock it, there should be none responded.
q.is_locked = True
q.save()
eq_(0, Question.objects.needs_attention().count())
self.assertEqual(0, Question.objects.needs_attention().count())
# Unlock it and mark solved, there should be none responded.
q.is_locked = False
q.solution = a
q.save()
eq_(0, Question.objects.needs_attention().count())
self.assertEqual(0, Question.objects.needs_attention().count())
def test_needs_info(self):
"""Verify the needs_info queryset."""
q = QuestionFactory()
# There should be no needs_info questions yet.
eq_(0, Question.objects.needs_info().count())
self.assertEqual(0, Question.objects.needs_info().count())
# Tag a question and there should be one needs_info question.
q.set_needs_info()
eq_(1, Question.objects.needs_info().count())
self.assertEqual(1, Question.objects.needs_info().count())
# Remove tag and there shouldn't be any anymore.
q.unset_needs_info()
eq_(0, Question.objects.needs_info().count())
self.assertEqual(0, Question.objects.needs_info().count())
class AnswerManagerTestCase(TestCase):
@ -102,8 +100,8 @@ class AnswerManagerTestCase(TestCase):
# Add an answer by the original asker
AnswerFactory(question=q, creator=q.creator)
eq_(0, Answer.objects.not_by_asker().count())
self.assertEqual(0, Answer.objects.not_by_asker().count())
# Add an answer by someone else
AnswerFactory(question=q)
eq_(1, Answer.objects.not_by_asker().count())
self.assertEqual(1, Answer.objects.not_by_asker().count())

Просмотреть файл

@ -5,7 +5,6 @@ from unittest import mock
from actstream.models import Action, Follow
from django.core.management import call_command
from django.db.models import Q
from nose.tools import eq_, ok_, raises
from taggit.models import Tag
import kitsune.sumo.models
@ -48,15 +47,15 @@ class TestAnswer(TestCaseBase):
q = QuestionFactory(title="Test Question", content="Lorem Ipsum Dolor")
updated = q.updated
eq_(0, q.num_answers)
eq_(None, q.last_answer)
self.assertEqual(0, q.num_answers)
self.assertEqual(None, q.last_answer)
a = AnswerFactory(question=q, content="Test Answer")
a.save()
q = Question.objects.get(pk=q.id)
eq_(1, q.num_answers)
eq_(a, q.last_answer)
self.assertEqual(1, q.num_answers)
self.assertEqual(a, q.last_answer)
self.assertNotEqual(updated, q.updated)
def test_delete_question_removes_flag(self):
@ -67,10 +66,10 @@ class TestAnswer(TestCaseBase):
FlaggedObject.objects.create(
status=0, content_object=q, reason="language", creator_id=u.id
)
eq_(1, FlaggedObject.objects.count())
self.assertEqual(1, FlaggedObject.objects.count())
q.delete()
eq_(0, FlaggedObject.objects.count())
self.assertEqual(0, FlaggedObject.objects.count())
def test_delete_answer_removes_flag(self):
"""Deleting an answer also removes the flags on that answer."""
@ -82,10 +81,10 @@ class TestAnswer(TestCaseBase):
FlaggedObject.objects.create(
status=0, content_object=a, reason="language", creator_id=u.id
)
eq_(1, FlaggedObject.objects.count())
self.assertEqual(1, FlaggedObject.objects.count())
a.delete()
eq_(0, FlaggedObject.objects.count())
self.assertEqual(0, FlaggedObject.objects.count())
def test_delete_last_answer_of_question(self):
"""Deleting the last_answer of a Question should update the question."""
@ -97,13 +96,13 @@ class TestAnswer(TestCaseBase):
a = AnswerFactory(question=q, content="Test Answer")
q = Question.objects.get(pk=q.id)
eq_(q.last_answer.id, a.id)
self.assertEqual(q.last_answer.id, a.id)
# delete the answer and last_answer should go back to previous value
a.delete()
q = Question.objects.get(pk=q.id)
eq_(q.last_answer.id, last_answer.id)
eq_(Answer.objects.filter(pk=a.id).count(), 0)
self.assertEqual(q.last_answer.id, last_answer.id)
self.assertEqual(Answer.objects.filter(pk=a.id).count(), 0)
def test_delete_solution_of_question(self):
"""Deleting the solution of a Question should update the question."""
@ -116,7 +115,7 @@ class TestAnswer(TestCaseBase):
# delete the solution and question.solution should go back to None
solution.delete()
q = Question.objects.get(pk=q.id)
eq_(q.solution, None)
self.assertEqual(q.solution, None)
def test_update_page_task(self):
a = AnswerFactory()
@ -141,10 +140,10 @@ class TestAnswer(TestCaseBase):
def test_creator_num_answers(self):
a = AnswerFactory()
eq_(a.creator_num_answers, 1)
self.assertEqual(a.creator_num_answers, 1)
AnswerFactory(creator=a.creator)
eq_(a.creator_num_answers, 2)
self.assertEqual(a.creator_num_answers, 2)
def test_creator_num_solutions(self):
a = AnswerFactory()
@ -153,7 +152,7 @@ class TestAnswer(TestCaseBase):
q.solution = a
q.save()
eq_(a.creator_num_solutions, 1)
self.assertEqual(a.creator_num_solutions, 1)
def test_content_parsed_with_locale(self):
"""Make sure links to localized articles work."""
@ -171,12 +170,12 @@ class TestAnswer(TestCaseBase):
# It's a pain to filter this from the DB, since follow_object is a
# ContentType field, so instead, do it in Python.
eq_(len(follows), 2)
self.assertEqual(len(follows), 2)
answer_follow = [f for f in follows if f.follow_object == a][0]
question_follow = [f for f in follows if f.follow_object == a.question][0]
eq_(question_follow.actor_only, False)
eq_(answer_follow.actor_only, False)
self.assertEqual(question_follow.actor_only, False)
self.assertEqual(answer_follow.actor_only, False)
class TestQuestionMetadata(TestCaseBase):
@ -193,23 +192,23 @@ class TestQuestionMetadata(TestCaseBase):
metadata = {"version": "3.6.3", "os": "Windows 7"}
self.question.add_metadata(**metadata)
saved = QuestionMetaData.objects.filter(question=self.question)
eq_(dict((x.name, x.value) for x in saved), metadata)
self.assertEqual(dict((x.name, x.value) for x in saved), metadata)
def test_metadata_property(self):
"""Test the metadata property on Question model."""
self.question.add_metadata(crash_id="1234567890")
eq_("1234567890", self.question.metadata["crash_id"])
self.assertEqual("1234567890", self.question.metadata["crash_id"])
def test_product_property(self):
"""Test question.product property."""
self.question.add_metadata(product="desktop")
eq_(config.products["desktop"], self.question.product_config)
self.assertEqual(config.products["desktop"], self.question.product_config)
def test_category_property(self):
"""Test question.category property."""
self.question.add_metadata(product="desktop")
self.question.add_metadata(category="fix-problems")
eq_(
self.assertEqual(
config.products["desktop"]["categories"]["fix-problems"],
self.question.category_config,
)
@ -233,7 +232,9 @@ class TestQuestionMetadata(TestCaseBase):
q.clear_mutable_metadata()
md = q.metadata
assert "crash_id" not in md, "clear_mutable_metadata() didn't clear the cached metadata."
eq_(dict(product="desktop", category="fix-problems", useragent="Fyerfocks"), md)
self.assertEqual(
dict(product="desktop", category="fix-problems", useragent="Fyerfocks"), md
)
def test_auto_tagging(self):
"""Make sure tags get applied based on metadata on first save."""
@ -263,9 +264,9 @@ class TestQuestionMetadata(TestCaseBase):
def test_tenths_version(self):
"""Test the filter that turns 1.2.3 into 1.2."""
eq_(_tenths_version("1.2.3beta3"), "1.2")
eq_(_tenths_version("1.2rc"), "1.2")
eq_(_tenths_version("1.w"), "")
self.assertEqual(_tenths_version("1.2.3beta3"), "1.2")
self.assertEqual(_tenths_version("1.2rc"), "1.2")
self.assertEqual(_tenths_version("1.w"), "")
def test_has_beta(self):
"""Test the _has_beta helper."""
@ -292,7 +293,7 @@ class QuestionTests(TestCaseBase):
q = QuestionFactory()
updated = q.updated
q.save()
eq_(updated, q.updated)
self.assertEqual(updated, q.updated)
def test_default_manager(self):
"""Assert Question's default manager is SUMO's ManagerBase.
@ -300,7 +301,7 @@ class QuestionTests(TestCaseBase):
This is easy to get wrong when mixing in taggability.
"""
eq_(
self.assertEqual(
Question._default_manager.__class__,
kitsune.questions.managers.QuestionManager,
)
@ -325,8 +326,8 @@ class QuestionTests(TestCaseBase):
QuestionFactory(created=now - timedelta(hours=25))
# Only 3 are recent from last 72 hours, 1 has an answer.
eq_(3, Question.recent_asked_count())
eq_(1, Question.recent_unanswered_count())
self.assertEqual(3, Question.recent_asked_count())
self.assertEqual(1, Question.recent_unanswered_count())
def test_recent_counts_with_filter(self):
"""Verify that recent_asked_count and recent_unanswered_count
@ -343,42 +344,42 @@ class QuestionTests(TestCaseBase):
AnswerFactory(question=q)
# 5 asked recently, 3 are unanswered
eq_(5, Question.recent_asked_count())
eq_(3, Question.recent_unanswered_count())
self.assertEqual(5, Question.recent_asked_count())
self.assertEqual(3, Question.recent_unanswered_count())
# check english (2 asked, 1 unanswered)
locale_filter = Q(locale="en-US")
eq_(2, Question.recent_asked_count(locale_filter))
eq_(1, Question.recent_unanswered_count(locale_filter))
self.assertEqual(2, Question.recent_asked_count(locale_filter))
self.assertEqual(1, Question.recent_unanswered_count(locale_filter))
# check pt-BR (3 asked, 2 unanswered)
locale_filter = Q(locale="pt-BR")
eq_(3, Question.recent_asked_count(locale_filter))
eq_(2, Question.recent_unanswered_count(locale_filter))
self.assertEqual(3, Question.recent_asked_count(locale_filter))
self.assertEqual(2, Question.recent_unanswered_count(locale_filter))
def test_from_url(self):
"""Verify question returned from valid URL."""
q = QuestionFactory()
eq_(q, Question.from_url("/en-US/questions/%s" % q.id))
eq_(q, Question.from_url("/es/questions/%s" % q.id))
eq_(q, Question.from_url("/questions/%s" % q.id))
self.assertEqual(q, Question.from_url("/en-US/questions/%s" % q.id))
self.assertEqual(q, Question.from_url("/es/questions/%s" % q.id))
self.assertEqual(q, Question.from_url("/questions/%s" % q.id))
def test_from_url_id_only(self):
"""Verify question returned from valid URL."""
# When requesting the id, the existence of the question isn't checked.
eq_(123, Question.from_url("/en-US/questions/123", id_only=True))
eq_(234, Question.from_url("/es/questions/234", id_only=True))
eq_(345, Question.from_url("/questions/345", id_only=True))
self.assertEqual(123, Question.from_url("/en-US/questions/123", id_only=True))
self.assertEqual(234, Question.from_url("/es/questions/234", id_only=True))
self.assertEqual(345, Question.from_url("/questions/345", id_only=True))
def test_from_invalid_url(self):
"""Verify question returned from valid URL."""
q = QuestionFactory()
eq_(None, Question.from_url("/en-US/questions/%s/edit" % q.id))
eq_(None, Question.from_url("/en-US/kb/%s" % q.id))
eq_(None, Question.from_url("/random/url"))
eq_(None, Question.from_url("/en-US/questions/dashboard/metrics"))
self.assertEqual(None, Question.from_url("/en-US/questions/%s/edit" % q.id))
self.assertEqual(None, Question.from_url("/en-US/kb/%s" % q.id))
self.assertEqual(None, Question.from_url("/random/url"))
self.assertEqual(None, Question.from_url("/en-US/questions/dashboard/metrics"))
def test_editable(self):
q = QuestionFactory()
@ -409,44 +410,44 @@ class QuestionTests(TestCaseBase):
def test_is_taken(self):
q = QuestionFactory()
u = UserFactory()
eq_(q.is_taken, False)
self.assertEqual(q.is_taken, False)
q.taken_by = u
q.taken_until = datetime.now() + timedelta(seconds=600)
q.save()
eq_(q.is_taken, True)
self.assertEqual(q.is_taken, True)
q.taken_by = None
q.taken_until = None
q.save()
eq_(q.is_taken, False)
self.assertEqual(q.is_taken, False)
def test_take(self):
u = UserFactory()
q = QuestionFactory()
q.take(u)
eq_(q.taken_by, u)
ok_(q.taken_until is not None)
self.assertEqual(q.taken_by, u)
assert q.taken_until is not None
@raises(InvalidUserException)
def test_take_creator(self):
q = QuestionFactory()
q.take(q.creator)
with self.assertRaises(InvalidUserException):
q.take(q.creator)
@raises(AlreadyTakenException)
def test_take_twice_fails(self):
u1 = UserFactory()
u2 = UserFactory()
q = QuestionFactory()
q.take(u1)
q.take(u2)
with self.assertRaises(AlreadyTakenException):
q.take(u2)
def test_take_twice_same_user_refreshes_time(self):
u = UserFactory()
first_taken_until = datetime.now() - timedelta(minutes=5)
q = QuestionFactory(taken_by=u, taken_until=first_taken_until)
q.take(u)
ok_(q.taken_until > first_taken_until)
assert q.taken_until > first_taken_until
def test_take_twice_forced(self):
u1 = UserFactory()
@ -454,7 +455,7 @@ class QuestionTests(TestCaseBase):
q = QuestionFactory()
q.take(u1)
q.take(u2, force=True)
eq_(q.taken_by, u2)
self.assertEqual(q.taken_by, u2)
def test_taken_until_is_set(self):
u = UserFactory()
@ -468,15 +469,15 @@ class QuestionTests(TestCaseBase):
q = QuestionFactory(taken_by=u, taken_until=taken_until)
# Testin q.is_taken should clear out ``taken_by`` and ``taken_until``,
# since taken_until is in the past.
eq_(q.is_taken, False)
eq_(q.taken_by, None)
eq_(q.taken_until, None)
self.assertEqual(q.is_taken, False)
self.assertEqual(q.taken_by, None)
self.assertEqual(q.taken_until, None)
def test_creator_follows(self):
q = QuestionFactory()
f = Follow.objects.get(user=q.creator)
eq_(f.follow_object, q)
eq_(f.actor_only, False)
self.assertEqual(f.follow_object, q)
self.assertEqual(f.actor_only, False)
class AddExistingTagTests(TestCaseBase):
@ -500,10 +501,10 @@ class AddExistingTagTests(TestCaseBase):
add_existing_tag("LEMON", self.untagged_question.tags)
tags_eq(self.untagged_question, ["lemon"])
@raises(Tag.DoesNotExist)
def test_add_existing_no_such_tag(self):
"""Assert add_existing_tag doesn't work when the tag doesn't exist."""
add_existing_tag("nonexistent tag", self.untagged_question.tags)
with self.assertRaises(Tag.DoesNotExist):
add_existing_tag("nonexistent tag", self.untagged_question.tags)
class OldQuestionsArchiveTest(Elastic7TestCase):
@ -530,18 +531,18 @@ class OldQuestionsArchiveTest(Elastic7TestCase):
call_command("auto_archive_old_questions")
# There are three questions.
eq_(len(list(Question.objects.all())), 3)
self.assertEqual(len(list(Question.objects.all())), 3)
# q2 and q3 are now archived and updated times are the same
archived_questions = list(Question.objects.filter(is_archived=True))
eq_(
self.assertEqual(
sorted([(q.id, q.updated.date()) for q in archived_questions]),
[(q.id, q.updated.date()) for q in [q2, q3]],
)
# q1 is still unarchived.
archived_questions = list(Question.objects.filter(is_archived=False))
eq_(sorted([q.id for q in archived_questions]), [q1.id])
self.assertEqual(sorted([q.id for q in archived_questions]), [q1.id])
class QuestionVisitsTests(TestCase):
@ -568,10 +569,10 @@ class QuestionVisitsTests(TestCase):
}
QuestionVisits.reload_from_analytics()
eq_(3, QuestionVisits.objects.count())
eq_(42, QuestionVisits.objects.get(question_id=q1.id).visits)
eq_(27, QuestionVisits.objects.get(question_id=q2.id).visits)
eq_(1337, QuestionVisits.objects.get(question_id=q3.id).visits)
self.assertEqual(3, QuestionVisits.objects.count())
self.assertEqual(42, QuestionVisits.objects.get(question_id=q1.id).visits)
self.assertEqual(27, QuestionVisits.objects.get(question_id=q2.id).visits)
self.assertEqual(1337, QuestionVisits.objects.get(question_id=q3.id).visits)
# Change the data and run again to cover the update case.
pageviews_by_question.return_value = {
@ -580,10 +581,10 @@ class QuestionVisitsTests(TestCase):
q3.id: 300,
}
QuestionVisits.reload_from_analytics()
eq_(3, QuestionVisits.objects.count())
eq_(100, QuestionVisits.objects.get(question_id=q1.id).visits)
eq_(200, QuestionVisits.objects.get(question_id=q2.id).visits)
eq_(300, QuestionVisits.objects.get(question_id=q3.id).visits)
self.assertEqual(3, QuestionVisits.objects.count())
self.assertEqual(100, QuestionVisits.objects.get(question_id=q1.id).visits)
self.assertEqual(200, QuestionVisits.objects.get(question_id=q2.id).visits)
self.assertEqual(300, QuestionVisits.objects.get(question_id=q3.id).visits)
class QuestionVoteTests(TestCase):
@ -591,7 +592,7 @@ class QuestionVoteTests(TestCase):
qv = QuestionVoteFactory()
qv.add_metadata("test1", "a" * 1001)
metadata = VoteMetadata.objects.all()[0]
eq_("a" * 1000, metadata.value)
self.assertEqual("a" * 1000, metadata.value)
class TestActions(TestCase):
@ -599,32 +600,32 @@ class TestActions(TestCase):
"""When a question is created, an Action is created too."""
q = QuestionFactory()
a = Action.objects.action_object(q).get()
eq_(a.actor, q.creator)
eq_(a.verb, "asked")
eq_(a.target, None)
self.assertEqual(a.actor, q.creator)
self.assertEqual(a.verb, "asked")
self.assertEqual(a.target, None)
def test_answer_create_action(self):
"""When an answer is created, an Action is created too."""
q = QuestionFactory()
ans = AnswerFactory(question=q)
act = Action.objects.action_object(ans).get()
eq_(act.actor, ans.creator)
eq_(act.verb, "answered")
eq_(act.target, q)
self.assertEqual(act.actor, ans.creator)
self.assertEqual(act.verb, "answered")
self.assertEqual(act.target, q)
def test_question_change_no_action(self):
"""When a question is changed, no Action should be created."""
q = QuestionFactory()
Action.objects.all().delete()
q.save() # trigger another post_save hook
eq_(Action.objects.count(), 0)
self.assertEqual(Action.objects.count(), 0)
def test_answer_change_no_action(self):
"""When an answer is changed, no Action should be created."""
q = QuestionFactory()
Action.objects.all().delete()
q.save() # trigger another post_save hook
eq_(Action.objects.count(), 0)
self.assertEqual(Action.objects.count(), 0)
def test_question_solved_makes_action(self):
"""When an answer is marked as the solution to a question, an Action should be created."""
@ -633,6 +634,6 @@ class TestActions(TestCase):
ans.question.set_solution(ans, ans.question.creator)
act = Action.objects.action_object(ans).get()
eq_(act.actor, ans.question.creator)
eq_(act.verb, "marked as a solution")
eq_(act.target, ans.question)
self.assertEqual(act.actor, ans.question.creator)
self.assertEqual(act.verb, "marked as a solution")
self.assertEqual(act.target, ans.question)

Просмотреть файл

@ -1,12 +1,10 @@
import re
from unittest import mock
from django.contrib.sites.models import Site
from django.core import mail
from django.test.utils import override_settings
from unittest import mock
from nose.tools import eq_
from kitsune.questions.events import QuestionReplyEvent, QuestionSolvedEvent
from kitsune.questions.models import Question
from kitsune.questions.tests import AnswerFactory, QuestionFactory, TestCaseBase
@ -273,7 +271,7 @@ class NotificationsTests(TestCaseBase):
event.fire(exclude=q.creator)
eq_("Solution found to Firefox Help question", mail.outbox[0].subject)
self.assertEqual("Solution found to Firefox Help question", mail.outbox[0].subject)
class TestAnswerNotifications(TestCaseBase):
@ -314,11 +312,11 @@ class TestAnswerNotifications(TestCaseBase):
self.makeAnswer()
# One for the asker's email, and one for the anonymous email.
eq_(2, len(mail.outbox))
self.assertEqual(2, len(mail.outbox))
notification = [m for m in mail.outbox if m.to == [ANON_EMAIL]][0]
eq_([ANON_EMAIL], notification.to)
eq_("Re: {0}".format(self.question.title), notification.subject)
self.assertEqual([ANON_EMAIL], notification.to)
self.assertEqual("Re: {0}".format(self.question.title), notification.subject)
body = re.sub(r"auth=[a-zA-Z0-9%_-]+", "auth=AUTH", notification.body)
starts_with(body, ANSWER_EMAIL_TO_ANONYMOUS.format(**self.format_args()))
@ -330,11 +328,11 @@ class TestAnswerNotifications(TestCaseBase):
self.makeAnswer()
# One for the asker's email, and one for the watcher's email.
eq_(2, len(mail.outbox))
self.assertEqual(2, len(mail.outbox))
notification = [m for m in mail.outbox if m.to == [watcher.email]][0]
eq_([watcher.email], notification.to)
eq_("Re: {0}".format(self.question.title), notification.subject)
self.assertEqual([watcher.email], notification.to)
self.assertEqual("Re: {0}".format(self.question.title), notification.subject)
body = re.sub(r"auth=[a-zA-Z0-9%_-]+", "auth=AUTH", notification.body)
starts_with(body, ANSWER_EMAIL.format(to_user=display_name(watcher), **self.format_args()))
@ -343,11 +341,11 @@ class TestAnswerNotifications(TestCaseBase):
"""Test that the answer is notified of answers, without registering."""
self.makeAnswer()
eq_(1, len(mail.outbox))
self.assertEqual(1, len(mail.outbox))
notification = mail.outbox[0]
eq_([self.question.creator.email], notification.to)
eq_(
self.assertEqual([self.question.creator.email], notification.to)
self.assertEqual(
'{0} posted an answer to your question "{1}"'.format(
display_name(self.answer.creator), self.question.title
),
@ -368,7 +366,7 @@ class TestAnswerNotifications(TestCaseBase):
notification = [m for m in mail.outbox if m.to == [ANON_EMAIL]][0]
# Headers should be compared case-insensitively.
headers = dict((k.lower(), v) for k, v in list(notification.extra_headers.items()))
eq_("replyto@example.com", headers["reply-to"])
self.assertEqual("replyto@example.com", headers["reply-to"])
@override_settings(DEFAULT_REPLY_TO_EMAIL="replyto@example.com")
def test_notify_arbitrary_reply_to(self):
@ -382,7 +380,7 @@ class TestAnswerNotifications(TestCaseBase):
notification = [m for m in mail.outbox if m.to == [watcher.email]][0]
# Headers should be compared case-insensitively.
headers = dict((k.lower(), v) for k, v in list(notification.extra_headers.items()))
eq_("replyto@example.com", headers["reply-to"])
self.assertEqual("replyto@example.com", headers["reply-to"])
@override_settings(DEFAULT_REPLY_TO_EMAIL="replyto@example.com")
def test_notify_asker_reply_to(self):
@ -392,4 +390,4 @@ class TestAnswerNotifications(TestCaseBase):
self.makeAnswer()
# Headers should be compared case-insensitively.
headers = dict((k.lower(), v) for k, v in list(mail.outbox[0].extra_headers.items()))
eq_("replyto@example.com", headers["reply-to"])
self.assertEqual("replyto@example.com", headers["reply-to"])

Просмотреть файл

@ -1,7 +1,5 @@
from django.db.models.signals import post_save
from nose.tools import eq_
from kitsune.questions.models import Question, QuestionVote, send_vote_update_task
from kitsune.questions.tasks import update_question_vote_chunk
from kitsune.questions.tests import QuestionFactory, QuestionVoteFactory
@ -27,13 +25,13 @@ class QuestionVoteTestCase(TestCase):
# Actually test the task.
qs = Question.objects.all().order_by("-num_votes_past_week")
eq_(q1.pk, qs[0].pk)
self.assertEqual(q1.pk, qs[0].pk)
QuestionVoteFactory(question=q2)
QuestionVoteFactory(question=q2)
qs = Question.objects.all().order_by("-num_votes_past_week")
eq_(q1.pk, qs[0].pk)
self.assertEqual(q1.pk, qs[0].pk)
update_question_vote_chunk([q.pk for q in qs])
qs = Question.objects.all().order_by("-num_votes_past_week")
eq_(q2.pk, qs[0].pk)
self.assertEqual(q2.pk, qs[0].pk)

Просмотреть файл

@ -9,7 +9,6 @@ from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.core.cache import cache
from nose.tools import eq_
from pyquery import PyQuery as pq
from taggit.models import Tag
from tidings.models import Watch
@ -63,14 +62,14 @@ class AnswersTemplateTestCase(TestCaseBase):
args=[self.question.id],
)
eq_(1, len(response.redirect_chain))
eq_(num_answers + 1, self.question.answers.count())
self.assertEqual(1, len(response.redirect_chain))
self.assertEqual(num_answers + 1, self.question.answers.count())
new_answer = self.question.answers.order_by("-id")[0]
eq_(content, new_answer.content)
self.assertEqual(content, new_answer.content)
# Check canonical url
doc = pq(response.content)
eq_(
self.assertEqual(
"%s/en-US/questions/%s" % (settings.CANONICAL_URL, self.question.id),
doc('link[rel="canonical"]')[0].attrib["href"],
)
@ -93,15 +92,15 @@ class AnswersTemplateTestCase(TestCaseBase):
{"content": content},
args=[self.question.id],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
new_answer = self.question.answers.order_by("-id")[0]
eq_(1, new_answer.images.count())
self.assertEqual(1, new_answer.images.count())
image = new_answer.images.all()[0]
name = "098f6b.png"
message = 'File name "%s" does not contain "%s"' % (image.file.name, name)
assert name in image.file.name, message
eq_(self.user.username, image.creator.username)
self.assertEqual(self.user.username, image.creator.username)
# Clean up
ImageAttachment.objects.all().delete()
@ -110,34 +109,34 @@ class AnswersTemplateTestCase(TestCaseBase):
"""Test accepting a solution and undoing."""
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(0, len(doc("div.solution")))
self.assertEqual(0, len(doc("div.solution")))
ans = self.question.answers.all()[0]
# Sign in as asker, solve and verify
self.client.login(username=self.question.creator.username, password="testpass")
response = post(self.client, "questions.solve", args=[self.question.id, ans.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(1, len(doc("div.solution")))
self.assertEqual(1, len(doc("div.solution")))
div = doc("h3.is-solution")[0].getparent().getparent()
eq_("answer-%s" % ans.id, div.attrib["id"])
self.assertEqual("answer-%s" % ans.id, div.attrib["id"])
q = Question.objects.get(pk=self.question.id)
eq_(q.solution, ans)
eq_(q.solver, self.question.creator)
self.assertEqual(q.solution, ans)
self.assertEqual(q.solver, self.question.creator)
# Try to solve again with different answer. It shouldn't blow up or
# change the solution.
AnswerFactory(question=q)
response = post(self.client, "questions.solve", args=[self.question.id, ans.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
q = Question.objects.get(pk=self.question.id)
eq_(q.solution, ans)
self.assertEqual(q.solution, ans)
# Unsolve and verify
response = post(self.client, "questions.unsolve", args=[self.question.id, ans.id])
q = Question.objects.get(pk=self.question.id)
eq_(q.solution, None)
eq_(q.solver, None)
self.assertEqual(q.solution, None)
self.assertEqual(q.solver, None)
def test_only_owner_or_admin_can_solve_unsolve(self):
"""Make sure non-owner/non-admin can't solve/unsolve."""
@ -145,7 +144,7 @@ class AnswersTemplateTestCase(TestCaseBase):
self.client.login(username=self.question.creator.username, password="testpass")
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(1, len(doc('input[name="solution"]')))
self.assertEqual(1, len(doc('input[name="solution"]')))
self.client.logout()
# Try as a nobody
@ -153,15 +152,15 @@ class AnswersTemplateTestCase(TestCaseBase):
self.client.login(username=u.username, password="testpass")
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(0, len(doc('input[name="solution"]')))
self.assertEqual(0, len(doc('input[name="solution"]')))
ans = self.question.answers.all()[0]
# Try to solve
response = post(self.client, "questions.solve", args=[self.question.id, ans.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
# Try to unsolve
response = post(self.client, "questions.unsolve", args=[self.question.id, ans.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_solve_unsolve_with_perm(self):
"""Test marking solve/unsolve with 'change_solution' permission."""
@ -172,30 +171,30 @@ class AnswersTemplateTestCase(TestCaseBase):
# Solve and verify
post(self.client, "questions.solve", args=[self.question.id, ans.id])
q = Question.objects.get(pk=self.question.id)
eq_(q.solution, ans)
eq_(q.solver, u)
self.assertEqual(q.solution, ans)
self.assertEqual(q.solver, u)
# Unsolve and verify
post(self.client, "questions.unsolve", args=[self.question.id, ans.id])
q = Question.objects.get(pk=self.question.id)
eq_(q.solution, None)
eq_(q.solver, None)
self.assertEqual(q.solution, None)
self.assertEqual(q.solver, None)
def test_needs_info_checkbox(self):
"""Test that needs info checkbox is correctly shown"""
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(1, len(doc('input[name="needsinfo"]')))
self.assertEqual(1, len(doc('input[name="needsinfo"]')))
self.question.set_needs_info()
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(1, len(doc('input[name="clear_needsinfo"]')))
self.assertEqual(1, len(doc('input[name="clear_needsinfo"]')))
def test_question_vote_GET(self):
"""Attempting to vote with HTTP GET returns a 405."""
response = get(self.client, "questions.vote", args=[self.question.id])
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
def common_vote(self, me_too_count=1):
"""Helper method for question vote tests."""
@ -203,7 +202,7 @@ class AnswersTemplateTestCase(TestCaseBase):
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
assert "0" in doc(".have-problem")[0].text
eq_(me_too_count, len(doc("div.me-too form")))
self.assertEqual(me_too_count, len(doc("div.me-too form")))
# Vote
ua = "Mozilla/5.0 (DjangoTestClient)"
@ -215,11 +214,11 @@ class AnswersTemplateTestCase(TestCaseBase):
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
assert "1" in doc(".have-problem")[0].text
eq_(0, len(doc("div.me-too form")))
self.assertEqual(0, len(doc("div.me-too form")))
# Verify user agent
vote_meta = VoteMetadata.objects.all()[0]
eq_("ua", vote_meta.key)
eq_(ua, vote_meta.value)
self.assertEqual("ua", vote_meta.key)
self.assertEqual(ua, vote_meta.value)
# Voting again (same user) should not increment vote count
post(self.client, "questions.vote", args=[self.question.id])
@ -245,7 +244,7 @@ class AnswersTemplateTestCase(TestCaseBase):
# Check that there are no votes and vote form renders
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(1, len(doc('form.helpful button[name="helpful"]')))
self.assertEqual(1, len(doc('form.helpful button[name="helpful"]')))
# Vote
ua = "Mozilla/5.0 (DjangoTestClient)"
@ -259,12 +258,12 @@ class AnswersTemplateTestCase(TestCaseBase):
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(1, len(doc("#answer-%s span.is-helpful" % self.answer.id)))
eq_(0, len(doc('form.helpful input[name="helpful"]')))
self.assertEqual(1, len(doc("#answer-%s span.is-helpful" % self.answer.id)))
self.assertEqual(0, len(doc('form.helpful input[name="helpful"]')))
# Verify user agent
vote_meta = VoteMetadata.objects.all()[0]
eq_("ua", vote_meta.key)
eq_(ua, vote_meta.value)
self.assertEqual("ua", vote_meta.key)
self.assertEqual(ua, vote_meta.value)
def test_answer_authenticated_vote(self):
"""Authenticated user answer vote."""
@ -292,7 +291,7 @@ class AnswersTemplateTestCase(TestCaseBase):
Answer.objects.create(question=q, creator=q.creator, content="test")
response = get(self.client, "questions.details", args=[q.id])
doc = pq(response.content)
eq_(2, len(doc('form.helpful button[name="helpful"]')))
self.assertEqual(2, len(doc('form.helpful button[name="helpful"]')))
def test_asker_can_vote(self):
"""The asker can vote Not/Helpful."""
@ -307,24 +306,24 @@ class AnswersTemplateTestCase(TestCaseBase):
Answer.objects.create(question=q, creator=q.creator, content="test")
response = get(self.client, "questions.details", args=[q.id])
doc = pq(response.content)
eq_(2, len(doc('form.solution input[name="solution"]')))
self.assertEqual(2, len(doc('form.solution input[name="solution"]')))
def test_delete_question_without_permissions(self):
"""Deleting a question without permissions is a 403."""
u = UserFactory()
self.client.login(username=u.username, password="testpass")
response = get(self.client, "questions.delete", args=[self.question.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
response = post(self.client, "questions.delete", args=[self.question.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_delete_question_logged_out(self):
"""Deleting a question while logged out redirects to login."""
self.client.logout()
response = get(self.client, "questions.delete", args=[self.question.id])
redirect = response.redirect_chain[0]
eq_(302, redirect[1])
eq_(
self.assertEqual(302, redirect[1])
self.assertEqual(
"/%s%s?next=/en-US/questions/%s/delete"
% (settings.LANGUAGE_CODE, settings.LOGIN_URL, self.question.id),
redirect[0],
@ -332,8 +331,8 @@ class AnswersTemplateTestCase(TestCaseBase):
response = post(self.client, "questions.delete", args=[self.question.id])
redirect = response.redirect_chain[0]
eq_(302, redirect[1])
eq_(
self.assertEqual(302, redirect[1])
self.assertEqual(
"/%s%s?next=/en-US/questions/%s/delete"
% (settings.LANGUAGE_CODE, settings.LOGIN_URL, self.question.id),
redirect[0],
@ -345,10 +344,10 @@ class AnswersTemplateTestCase(TestCaseBase):
add_permission(u, Question, "delete_question")
self.client.login(username=u.username, password="testpass")
response = get(self.client, "questions.delete", args=[self.question.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
response = post(self.client, "questions.delete", args=[self.question.id])
eq_(0, Question.objects.filter(pk=self.question.id).count())
self.assertEqual(0, Question.objects.filter(pk=self.question.id).count())
def test_delete_answer_without_permissions(self):
"""Deleting an answer without permissions sends 403."""
@ -356,10 +355,10 @@ class AnswersTemplateTestCase(TestCaseBase):
self.client.login(username=u.username, password="testpass")
ans = self.question.last_answer
response = get(self.client, "questions.delete_answer", args=[self.question.id, ans.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
response = post(self.client, "questions.delete_answer", args=[self.question.id, ans.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_delete_answer_logged_out(self):
"""Deleting an answer while logged out redirects to login."""
@ -368,8 +367,8 @@ class AnswersTemplateTestCase(TestCaseBase):
ans = q.last_answer
response = get(self.client, "questions.delete_answer", args=[self.question.id, ans.id])
redirect = response.redirect_chain[0]
eq_(302, redirect[1])
eq_(
self.assertEqual(302, redirect[1])
self.assertEqual(
"/%s%s?next=/en-US/questions/%s/delete/%s"
% (settings.LANGUAGE_CODE, settings.LOGIN_URL, q.id, ans.id),
redirect[0],
@ -377,8 +376,8 @@ class AnswersTemplateTestCase(TestCaseBase):
response = post(self.client, "questions.delete_answer", args=[self.question.id, ans.id])
redirect = response.redirect_chain[0]
eq_(302, redirect[1])
eq_(
self.assertEqual(302, redirect[1])
self.assertEqual(
"/%s%s?next=/en-US/questions/%s/delete/%s"
% (settings.LANGUAGE_CODE, settings.LOGIN_URL, q.id, ans.id),
redirect[0],
@ -391,10 +390,10 @@ class AnswersTemplateTestCase(TestCaseBase):
add_permission(u, Answer, "delete_answer")
self.client.login(username=u.username, password="testpass")
response = get(self.client, "questions.delete_answer", args=[self.question.id, ans.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
response = post(self.client, "questions.delete_answer", args=[self.question.id, ans.id])
eq_(0, Answer.objects.filter(pk=self.question.id).count())
self.assertEqual(0, Answer.objects.filter(pk=self.question.id).count())
def test_edit_answer_without_permission(self):
"""Editing an answer without permissions returns a 403.
@ -402,11 +401,11 @@ class AnswersTemplateTestCase(TestCaseBase):
The edit link shouldn't show up on the Answers page."""
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(0, len(doc("ol.answers li.edit")))
self.assertEqual(0, len(doc("ol.answers li.edit")))
answer = self.question.last_answer
response = get(self.client, "questions.edit_answer", args=[self.question.id, answer.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
content = "New content for answer"
response = post(
@ -415,7 +414,7 @@ class AnswersTemplateTestCase(TestCaseBase):
{"content": content},
args=[self.question.id, answer.id],
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_edit_answer_with_permissions(self):
"""Editing an answer with permissions.
@ -427,11 +426,11 @@ class AnswersTemplateTestCase(TestCaseBase):
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(1, len(doc("li.edit")))
self.assertEqual(1, len(doc("li.edit")))
answer = self.question.last_answer
response = get(self.client, "questions.edit_answer", args=[self.question.id, answer.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
content = "New content for answer"
response = post(
@ -440,7 +439,7 @@ class AnswersTemplateTestCase(TestCaseBase):
{"content": content},
args=[self.question.id, answer.id],
)
eq_(content, Answer.objects.get(pk=answer.id).content)
self.assertEqual(content, Answer.objects.get(pk=answer.id).content)
def test_answer_creator_can_edit(self):
"""The creator of an answer can edit his/her answer."""
@ -450,7 +449,7 @@ class AnswersTemplateTestCase(TestCaseBase):
# Initially there should be no edit links
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(0, len(doc("ul.mzp-c-menu-list-list li.edit")))
self.assertEqual(0, len(doc("ul.mzp-c-menu-list-list li.edit")))
# Add an answer and verify the edit link shows up
content = "lorem ipsum dolor sit amet"
@ -461,9 +460,9 @@ class AnswersTemplateTestCase(TestCaseBase):
args=[self.question.id],
)
doc = pq(response.content)
eq_(1, len(doc("li.edit")))
self.assertEqual(1, len(doc("li.edit")))
new_answer = self.question.answers.order_by("-id")[0]
eq_(1, len(doc("#answer-%s li.edit" % new_answer.id)))
self.assertEqual(1, len(doc("#answer-%s li.edit" % new_answer.id)))
# Make sure it can be edited
content = "New content for answer"
@ -473,7 +472,7 @@ class AnswersTemplateTestCase(TestCaseBase):
{"content": content},
args=[self.question.id, new_answer.id],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
# Now lock it and make sure it can't be edited
self.question.is_locked = True
@ -484,7 +483,7 @@ class AnswersTemplateTestCase(TestCaseBase):
{"content": content},
args=[self.question.id, new_answer.id],
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_lock_question_without_permissions(self):
"""Trying to lock a question without permission is a 403."""
@ -492,7 +491,7 @@ class AnswersTemplateTestCase(TestCaseBase):
self.client.login(username=u.username, password="testpass")
q = self.question
response = post(self.client, "questions.lock", args=[q.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_lock_question_logged_out(self):
"""Trying to lock a question while logged out redirects to login."""
@ -500,8 +499,8 @@ class AnswersTemplateTestCase(TestCaseBase):
q = self.question
response = post(self.client, "questions.lock", args=[q.id])
redirect = response.redirect_chain[0]
eq_(302, redirect[1])
eq_(
self.assertEqual(302, redirect[1])
self.assertEqual(
"/%s%s?next=/en-US/questions/%s/lock"
% (settings.LANGUAGE_CODE, settings.LOGIN_URL, q.id),
redirect[0],
@ -513,7 +512,7 @@ class AnswersTemplateTestCase(TestCaseBase):
add_permission(u, Question, "lock_question")
self.client.login(username=u.username, password="testpass")
response = get(self.client, "questions.lock", args=[self.question.id])
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
def test_lock_question_with_permissions_POST(self):
"""Locking questions with permissions via HTTP POST."""
@ -522,14 +521,14 @@ class AnswersTemplateTestCase(TestCaseBase):
self.client.login(username=u.username, password="testpass")
q = self.question
response = post(self.client, "questions.lock", args=[q.id])
eq_(200, response.status_code)
eq_(True, Question.objects.get(pk=q.pk).is_locked)
self.assertEqual(200, response.status_code)
self.assertEqual(True, Question.objects.get(pk=q.pk).is_locked)
assert b"This thread was closed." in response.content
# now unlock it
response = post(self.client, "questions.lock", args=[q.id])
eq_(200, response.status_code)
eq_(False, Question.objects.get(pk=q.pk).is_locked)
self.assertEqual(200, response.status_code)
self.assertEqual(False, Question.objects.get(pk=q.pk).is_locked)
def test_reply_to_locked_question(self):
"""Locked questions can't be answered."""
@ -541,12 +540,12 @@ class AnswersTemplateTestCase(TestCaseBase):
q.is_locked = True
q.save()
response = post(self.client, "questions.reply", {"content": "just testing"}, args=[q.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
# With add_answer permission, it should work.
add_permission(u, Answer, "add_answer")
response = post(self.client, "questions.reply", {"content": "just testing"}, args=[q.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_edit_answer_locked_question(self):
"""Verify edit answer of a locked question only with permissions."""
@ -559,11 +558,11 @@ class AnswersTemplateTestCase(TestCaseBase):
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(0, len(doc("li.edit")))
self.assertEqual(0, len(doc("li.edit")))
answer = self.question.last_answer
response = get(self.client, "questions.edit_answer", args=[self.question.id, answer.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
# A user with edit_answer permission can edit.
u = UserFactory()
@ -572,11 +571,11 @@ class AnswersTemplateTestCase(TestCaseBase):
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(1, len(doc("li.edit")))
self.assertEqual(1, len(doc("li.edit")))
answer = self.question.last_answer
response = get(self.client, "questions.edit_answer", args=[self.question.id, answer.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
content = "New content for answer"
response = post(
@ -585,7 +584,7 @@ class AnswersTemplateTestCase(TestCaseBase):
{"content": content},
args=[self.question.id, answer.id],
)
eq_(content, Answer.objects.get(pk=answer.id).content)
self.assertEqual(content, Answer.objects.get(pk=answer.id).content)
def test_vote_locked_question_403(self):
"""Locked questions can't be voted on."""
@ -596,7 +595,7 @@ class AnswersTemplateTestCase(TestCaseBase):
q.is_locked = True
q.save()
response = post(self.client, "questions.vote", args=[q.id])
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_vote_answer_to_locked_question_403(self):
"""Answers to locked questions can't be voted on."""
@ -612,21 +611,21 @@ class AnswersTemplateTestCase(TestCaseBase):
{"helpful": "y"},
args=[q.id, self.answer.id],
)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_watch_GET_405(self):
"""Watch replies with HTTP GET results in 405."""
u = UserFactory()
self.client.login(username=u.username, password="testpass")
response = get(self.client, "questions.watch", args=[self.question.id])
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
def test_unwatch_GET_405(self):
"""Unwatch replies with HTTP GET results in 405."""
u = UserFactory()
self.client.login(username=u.username, password="testpass")
response = get(self.client, "questions.unwatch", args=[self.question.id])
eq_(405, response.status_code)
self.assertEqual(405, response.status_code)
def test_watch_replies(self):
"""Watch a question for replies."""
@ -693,7 +692,7 @@ class AnswersTemplateTestCase(TestCaseBase):
# Now activate the watch.
w = Watch.objects.get()
r = get(self.client, "questions.activate_watch", args=[w.id, "fail"])
eq_(200, r.status_code)
self.assertEqual(200, r.status_code)
assert not Watch.objects.get(id=w.id).is_active
def test_watch_replies_logged_in(self):
@ -756,7 +755,7 @@ class AnswersTemplateTestCase(TestCaseBase):
QuestionReplyEvent.notify(u, self.question)
QuestionSolvedEvent.notify(u, self.question)
response = get(self.client, "questions.details", args=[self.question.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_preview_answer(self):
"""Preview an answer."""
@ -768,10 +767,10 @@ class AnswersTemplateTestCase(TestCaseBase):
{"content": content, "preview": "any string"},
args=[self.question.id],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(content, doc("#answer-preview div.content").text())
eq_(num_answers, self.question.answers.count())
self.assertEqual(content, doc("#answer-preview div.content").text())
self.assertEqual(num_answers, self.question.answers.count())
def test_preview_answer_as_admin(self):
"""Preview an answer as admin and verify response is 200."""
@ -784,7 +783,7 @@ class AnswersTemplateTestCase(TestCaseBase):
{"content": content, "preview": "any string"},
args=[self.question.id],
)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_links_nofollow(self):
"""Links posted in questions and answers should have rel=nofollow."""
@ -796,8 +795,8 @@ class AnswersTemplateTestCase(TestCaseBase):
a.save()
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_("nofollow", doc(".question .main-content a")[0].attrib["rel"])
eq_("nofollow", doc(".answer .main-content a")[0].attrib["rel"])
self.assertEqual("nofollow", doc(".question .main-content a")[0].attrib["rel"])
self.assertEqual("nofollow", doc(".answer .main-content a")[0].attrib["rel"])
def test_robots_noindex_unsolved(self):
"""Verify noindex on unsolved questions."""
@ -805,25 +804,25 @@ class AnswersTemplateTestCase(TestCaseBase):
# A brand new questions should be noindexed...
response = get(self.client, "questions.details", args=[q.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(1, len(doc("meta[name=robots]")))
self.assertEqual(1, len(doc("meta[name=robots]")))
# If it has one answer, it should still be noindexed...
a = AnswerFactory(question=q)
response = get(self.client, "questions.details", args=[q.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(1, len(doc("meta[name=robots]")))
self.assertEqual(1, len(doc("meta[name=robots]")))
# If the answer is the solution, then it shouldn't be noindexed
# anymore.
q.solution = a
q.save()
response = get(self.client, "questions.details", args=[q.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(0, len(doc("meta[name=robots]")))
self.assertEqual(0, len(doc("meta[name=robots]")))
class TaggingViewTestsAsTagger(TestCaseBase):
@ -901,7 +900,7 @@ class TaggingViewTestsAsTagger(TestCaseBase):
# Test the backend since we don't have a newly rendered page to
# rely on.
eq_([t.name for t in tags], ["purplepurplepurple"])
self.assertEqual([t.name for t in tags], ["purplepurplepurple"])
def test_add_async_no_tag(self):
"""Assert adding an empty tag asynchronously yields an AJAX error."""
@ -923,7 +922,7 @@ class TaggingViewTestsAsTagger(TestCaseBase):
)
self._assert_redirects_to_question(response, self.question.id)
tags = Question.objects.get(pk=self.question.id).tags.all()
eq_([t.name for t in tags], ["green"])
self.assertEqual([t.name for t in tags], ["green"])
def test_remove_unapplied_tag(self):
"""Test removing an unapplied tag fails silently."""
@ -954,9 +953,9 @@ class TaggingViewTestsAsTagger(TestCaseBase):
data={"name": "colorless"},
HTTP_X_REQUESTED_WITH="XMLHttpRequest",
)
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
tags = Question.objects.get(pk=self.question.id).tags.all()
eq_([t.name for t in tags], ["green"])
self.assertEqual([t.name for t in tags], ["green"])
def test_remove_async_unapplied_tag(self):
"""Assert trying to remove a tag that isn't there succeeds."""
@ -965,7 +964,7 @@ class TaggingViewTestsAsTagger(TestCaseBase):
data={"name": "lemon"},
HTTP_X_REQUESTED_WITH="XMLHttpRequest",
)
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
def test_remove_async_no_tag(self):
"""Assert calling the remove handler with no param fails."""
@ -1003,7 +1002,7 @@ class TaggingViewTestsAsAdmin(TestCaseBase):
data={"tag-name": "nonexistent tag"},
HTTP_X_REQUESTED_WITH="XMLHttpRequest",
)
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
tags_eq(Question.objects.get(id=self.question.id), ["nonexistent tag"])
def test_add_new_case_insensitive(self):
@ -1023,7 +1022,7 @@ class TaggingViewTestsAsAdmin(TestCaseBase):
data={"tag-name": "RED"},
HTTP_X_REQUESTED_WITH="XMLHttpRequest",
)
eq_(json.loads(response.content)["canonicalName"], "red")
self.assertEqual(json.loads(response.content)["canonicalName"], "red")
def _add_tag_url(question_id):
@ -1058,12 +1057,12 @@ class QuestionsTemplateTestCase(TestCaseBase):
# First there should be no questions tagged 'mobile'
response = self.client.get(tagged)
doc = pq(response.content)
eq_(0, len(doc(".forum--question-item")))
self.assertEqual(0, len(doc(".forum--question-item")))
# Tag a question 'mobile'
q = QuestionFactory()
response = post(self.client, "questions.add_tag", {"tag-name": tagname}, args=[q.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
# Add an answer
AnswerFactory(question=q)
@ -1071,8 +1070,8 @@ class QuestionsTemplateTestCase(TestCaseBase):
# Now there should be 1 question tagged 'mobile'
response = self.client.get(tagged)
doc = pq(response.content)
eq_(1, len(doc(".forum--question-item")))
eq_(
self.assertEqual(1, len(doc(".forum--question-item")))
self.assertEqual(
"%s/en-US/questions/all?tagged=mobile&show=all" % settings.CANONICAL_URL,
doc('link[rel="canonical"]')[0].attrib["href"],
)
@ -1082,14 +1081,14 @@ class QuestionsTemplateTestCase(TestCaseBase):
reverse("questions.list", args=["all"]), tagged="garbage-plate", show="all"
)
response = self.client.get(url)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_owner_tab_selected_in_list(self):
# Test one tab is selected for no show arg specified
questions_list = urlparams(reverse("questions.list", args=["all"]))
response = self.client.get(questions_list)
doc = pq(response.content)
eq_(1, len(doc("#owner-tabs .selected")))
self.assertEqual(1, len(doc("#owner-tabs .selected")))
# Test one tab is selected for all show args
show_args = ["needs-attention", "responded", "done", "all"]
@ -1097,7 +1096,7 @@ class QuestionsTemplateTestCase(TestCaseBase):
questions_list = urlparams(reverse("questions.list", args=["all"]), show=show_arg)
response = self.client.get(questions_list)
doc = pq(response.content)
eq_(1, len(doc("#owner-tabs .selected")))
self.assertEqual(1, len(doc("#owner-tabs .selected")))
def test_product_filter(self):
p1 = ProductFactory()
@ -1118,10 +1117,10 @@ class QuestionsTemplateTestCase(TestCaseBase):
# This won't work, because the test case base adds more tests than
# we expect in it's setUp(). TODO: Fix that.
eq_(len(expected), len(doc(".forum--question-item")))
self.assertEqual(len(expected), len(doc(".forum--question-item")))
for q in expected:
eq_(1, len(doc(".forum--question-item[id=question-%s]" % q.id)))
self.assertEqual(1, len(doc(".forum--question-item[id=question-%s]" % q.id)))
# No filtering -> All questions.
check("all", [q1, q2, q3])
@ -1157,10 +1156,10 @@ class QuestionsTemplateTestCase(TestCaseBase):
# This won't work, because the test case base adds more tests than
# we expect in it's setUp(). TODO: Fix that.
# eq_(len(expected), len(doc('.forum--question-item')))
# self.assertEqual(len(expected), len(doc('.forum--question-item')))
for q in expected:
eq_(1, len(doc(".forum--question-item[id=question-%s]" % q.id)))
self.assertEqual(1, len(doc(".forum--question-item[id=question-%s]" % q.id)))
# No filtering -> All questions.
check({}, [q1, q2, q3])
@ -1174,9 +1173,9 @@ class QuestionsTemplateTestCase(TestCaseBase):
def test_robots_noindex(self):
"""Verify the page is set for noindex by robots."""
response = self.client.get(reverse("questions.list", args=["all"]))
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(1, len(doc("meta[name=robots]")))
self.assertEqual(1, len(doc("meta[name=robots]")))
def test_select_in_question(self):
"""Verify we properly escape <select/>."""
@ -1188,7 +1187,7 @@ class QuestionsTemplateTestCase(TestCaseBase):
assert b"test question lorem ipsum" in response.content
assert b"test question content lorem ipsum" in response.content
doc = pq(response.content)
eq_(0, len(doc("article.questions select")))
self.assertEqual(0, len(doc("article.questions select")))
def test_truncated_text_is_stripped(self):
"""Verify we strip html from truncated text."""
@ -1206,7 +1205,7 @@ class QuestionsTemplateTestCase(TestCaseBase):
q.questionvisits_set.create(visits=1007)
response = self.client.get(reverse("questions.list", args=["all"]))
doc = pq(response.content)
eq_("1007", doc(".views-val").text())
self.assertEqual("1007", doc(".views-val").text())
def test_no_unarchive_on_old_questions(self):
ques = QuestionFactory(created=(datetime.now() - timedelta(days=200)), is_archived=True)
@ -1216,7 +1215,7 @@ class QuestionsTemplateTestCase(TestCaseBase):
def test_show_is_empty_string_doesnt_500(self):
QuestionFactory()
response = self.client.get(urlparams(reverse("questions.list", args=["all"]), show=""))
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_product_shows_without_tags(self):
p = ProductFactory()
@ -1243,7 +1242,7 @@ class QuestionsTemplateTestCaseNoFixtures(TestCase):
url = urlparams(url, filter="no-replies")
response = self.client.get(url)
doc = pq(response.content)
eq_(2, len(doc(".forum--question-item")))
self.assertEqual(2, len(doc(".forum--question-item")))
class QuestionEditingTests(TestCaseBase):
@ -1260,7 +1259,7 @@ class QuestionEditingTests(TestCaseBase):
"""The edit-question form should show appropriate metadata fields."""
question_id = QuestionFactory().id
response = get(self.client, "questions.edit_question", kwargs={"question_id": question_id})
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
# Make sure each extra metadata field is in the form:
doc = pq(response.content)
@ -1277,7 +1276,7 @@ class QuestionEditingTests(TestCaseBase):
"""The edit-question form shouldn't show inappropriate metadata."""
question_id = QuestionFactory().id
response = get(self.client, "questions.edit_question", kwargs={"question_id": question_id})
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
# Take the "os" field as representative. Make sure it doesn't show up:
doc = pq(response.content)
@ -1305,9 +1304,9 @@ class QuestionEditingTests(TestCaseBase):
# Make sure the static fields, the metadata, and the updated_by field
# changed:
q = Question.objects.get(pk=q.id)
eq_(q.title, "New title")
eq_(q.content, "New content")
eq_(q.updated_by, self.user)
self.assertEqual(q.title, "New title")
self.assertEqual(q.content, "New content")
self.assertEqual(q.updated_by, self.user)
class AAQTemplateTestCase(TestCaseBase):
@ -1373,7 +1372,7 @@ class AAQTemplateTestCase(TestCaseBase):
def test_full_workflow(self):
response = self._post_new_question()
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
assert "Done!" in pq(response.content)("ul.user-messages li").text()
# Verify question is in db now
@ -1382,13 +1381,13 @@ class AAQTemplateTestCase(TestCaseBase):
# Make sure question is in questions list
response = self.client.get(reverse("questions.list", args=["all"]))
doc = pq(response.content)
eq_(1, len(doc("#question-%s" % question.id)))
self.assertEqual(1, len(doc("#question-%s" % question.id)))
# And no email was sent
eq_(0, len(mail.outbox))
self.assertEqual(0, len(mail.outbox))
# Verify product and topic assigned to question.
eq_("fix-problems", question.topic.slug)
eq_("firefox", question.product.slug)
self.assertEqual("fix-problems", question.topic.slug)
self.assertEqual("firefox", question.product.slug)
# Verify troubleshooting information
troubleshooting = question.metadata["troubleshooting"]
@ -1397,7 +1396,7 @@ class AAQTemplateTestCase(TestCaseBase):
# Verify firefox version
version = question.metadata["ff_version"]
eq_("18.0.2", version)
self.assertEqual("18.0.2", version)
def test_full_workflow_inactive(self):
"""
@ -1407,27 +1406,27 @@ class AAQTemplateTestCase(TestCaseBase):
u.is_active = False
u.save()
self._post_new_question()
eq_(0, Question.objects.count())
self.assertEqual(0, Question.objects.count())
def test_localized_creation(self):
response = self._post_new_question(locale="pt-BR")
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
assert "Done!" in pq(response.content)("ul.user-messages li").text()
# Verify question is in db now
question = Question.objects.filter(title="A test question")[0]
eq_(question.locale, "pt-BR")
self.assertEqual(question.locale, "pt-BR")
def test_invalid_product_404(self):
url = reverse("questions.aaq_step2", args=["lipsum"])
response = self.client.get(url)
eq_(404, response.status_code)
self.assertEqual(404, response.status_code)
def test_invalid_category_302(self):
ProductFactory(slug="firefox")
url = reverse("questions.aaq_step3", args=["desktop", "lipsum"])
response = self.client.get(url)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
class ProductForumTemplateTestCase(TestCaseBase):
@ -1443,9 +1442,9 @@ class ProductForumTemplateTestCase(TestCaseBase):
fxos.questions_locales.add(lcl)
response = self.client.get(reverse("questions.home"))
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
doc = pq(response.content)
eq_(4, len(doc(".product-list .product")))
self.assertEqual(4, len(doc(".product-list .product")))
product_list_html = doc(".product-list").html()
assert firefox.title in product_list_html
assert android.title in product_list_html
@ -1465,7 +1464,7 @@ class RelatedThingsTestCase(Elastic7TestCase):
def test_related_questions(self):
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(0, len(doc("#related-content .related-question")))
self.assertEqual(0, len(doc("#related-content .related-question")))
q1 = QuestionFactory(
title="lorem ipsum dolor", content="lorem", product=self.question.product
@ -1488,12 +1487,12 @@ class RelatedThingsTestCase(Elastic7TestCase):
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(1, len(doc("#related-content .related-question")))
self.assertEqual(1, len(doc("#related-content .related-question")))
def test_related_documents(self):
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(0, len(doc("#related-content .related-document")))
self.assertEqual(0, len(doc("#related-content .related-document")))
d1 = DocumentFactory(title="lorem ipsum")
d1.products.add(self.question.product)
@ -1505,4 +1504,4 @@ class RelatedThingsTestCase(Elastic7TestCase):
response = get(self.client, "questions.details", args=[self.question.id])
doc = pq(response.content)
eq_(1, len(doc("#related-content .related-document")))
self.assertEqual(1, len(doc("#related-content .related-document")))

Просмотреть файл

@ -1,4 +1,3 @@
from nose.tools import eq_
from parameterized import parameterized
from kitsune.questions.models import Answer, Question
@ -18,36 +17,36 @@ class ContributionCountTestCase(TestCase):
def test_num_questions(self):
"""Answers are counted correctly on a user."""
u = UserFactory()
eq_(num_questions(u), 0)
self.assertEqual(num_questions(u), 0)
q1 = QuestionFactory(creator=u)
eq_(num_questions(u), 1)
self.assertEqual(num_questions(u), 1)
q2 = QuestionFactory(creator=u)
eq_(num_questions(u), 2)
self.assertEqual(num_questions(u), 2)
q1.delete()
eq_(num_questions(u), 1)
self.assertEqual(num_questions(u), 1)
q2.delete()
eq_(num_questions(u), 0)
self.assertEqual(num_questions(u), 0)
def test_num_answers(self):
u = UserFactory()
q = QuestionFactory()
eq_(num_answers(u), 0)
self.assertEqual(num_answers(u), 0)
a1 = AnswerFactory(creator=u, question=q)
eq_(num_answers(u), 1)
self.assertEqual(num_answers(u), 1)
a2 = AnswerFactory(creator=u, question=q)
eq_(num_answers(u), 2)
self.assertEqual(num_answers(u), 2)
a1.delete()
eq_(num_answers(u), 1)
self.assertEqual(num_answers(u), 1)
a2.delete()
eq_(num_answers(u), 0)
self.assertEqual(num_answers(u), 0)
def test_num_solutions(self):
u = UserFactory()
@ -55,22 +54,22 @@ class ContributionCountTestCase(TestCase):
q2 = QuestionFactory()
a1 = AnswerFactory(creator=u, question=q1)
a2 = AnswerFactory(creator=u, question=q2)
eq_(num_solutions(u), 0)
self.assertEqual(num_solutions(u), 0)
q1.solution = a1
q1.save()
eq_(num_solutions(u), 1)
self.assertEqual(num_solutions(u), 1)
q2.solution = a2
q2.save()
eq_(num_solutions(u), 2)
self.assertEqual(num_solutions(u), 2)
q1.solution = None
q1.save()
eq_(num_solutions(u), 1)
self.assertEqual(num_solutions(u), 1)
a2.delete()
eq_(num_solutions(u), 0)
self.assertEqual(num_solutions(u), 0)
class FlagUserContentAsSpamTestCase(TestCase):
@ -84,17 +83,17 @@ class FlagUserContentAsSpamTestCase(TestCase):
AnswerFactory(creator=u)
# Verify they are not marked as spam yet.
eq_(2, Question.objects.filter(is_spam=False, creator=u).count())
eq_(0, Question.objects.filter(is_spam=True, creator=u).count())
eq_(3, Answer.objects.filter(is_spam=False, creator=u).count())
eq_(0, Answer.objects.filter(is_spam=True, creator=u).count())
self.assertEqual(2, Question.objects.filter(is_spam=False, creator=u).count())
self.assertEqual(0, Question.objects.filter(is_spam=True, creator=u).count())
self.assertEqual(3, Answer.objects.filter(is_spam=False, creator=u).count())
self.assertEqual(0, Answer.objects.filter(is_spam=True, creator=u).count())
# Flag content as spam and verify it is updated.
mark_content_as_spam(u, UserFactory())
eq_(0, Question.objects.filter(is_spam=False, creator=u).count())
eq_(2, Question.objects.filter(is_spam=True, creator=u).count())
eq_(0, Answer.objects.filter(is_spam=False, creator=u).count())
eq_(3, Answer.objects.filter(is_spam=True, creator=u).count())
self.assertEqual(0, Question.objects.filter(is_spam=False, creator=u).count())
self.assertEqual(2, Question.objects.filter(is_spam=True, creator=u).count())
self.assertEqual(0, Answer.objects.filter(is_spam=False, creator=u).count())
self.assertEqual(3, Answer.objects.filter(is_spam=True, creator=u).count())
class GetMobileProductFromUATests(TestCase):
@ -123,4 +122,4 @@ class GetMobileProductFromUATests(TestCase):
]
)
def test_user_agents(self, ua, expected):
eq_(expected, get_mobile_product_from_ua(ua))
self.assertEqual(expected, get_mobile_product_from_ua(ua))

Просмотреть файл

@ -3,7 +3,6 @@ from datetime import datetime, timedelta
from django.conf import settings
from django.test.utils import override_settings
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.flagit.models import FlaggedObject
@ -47,7 +46,7 @@ class AAQSearchTests(Elastic7TestCase):
)
response = self.client.get(url, follow=True)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
assert b"CupcakesQuestion" in response.content
assert b"<unbleached>" not in response.content
@ -72,7 +71,7 @@ class AAQSearchTests(Elastic7TestCase):
)
response = self.client.get(url, follow=True)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
assert b"CupcakesQuestion" in response.content
@ -83,7 +82,7 @@ class AAQSearchTests(Elastic7TestCase):
self.refresh()
response = self.client.get(url, follow=True)
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
assert b"CupcakesQuestion" not in response.content
@ -157,7 +156,7 @@ class AAQSearchTests(Elastic7TestCase):
self.client.post(url, data, follow=True)
response = self.client.post(url, data, follow=True)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
def test_first_step(self):
"""Make sure the first step doesn't blow up
@ -166,14 +165,14 @@ class AAQSearchTests(Elastic7TestCase):
"""
url = reverse("questions.aaq_step1")
res = self.client.get(url)
eq_(200, res.status_code)
self.assertEqual(200, res.status_code)
def test_redirect_bad_locales(self):
"""Non-AAQ locales should redirect."""
url_fr = reverse("questions.aaq_step1", locale="fr")
url_en = reverse("questions.aaq_step1", locale="en-US")
res = self.client.get(url_fr)
eq_(302, res.status_code)
self.assertEqual(302, res.status_code)
# This has some http://... stuff at the beginning. Ignore that.
assert res["location"].endswith(url_en)
@ -183,27 +182,27 @@ class AAQSearchTests(Elastic7TestCase):
"""Non-AAQ locales should redirect."""
url_fr = reverse("questions.aaq_step1", locale="fr")
res = self.client.get(url_fr)
eq_(200, res.status_code)
self.assertEqual(200, res.status_code)
def test_redirect_locale_not_enabled(self):
"""AAQ should redirect for products with questions disabled for the
current locale"""
url_fi = reverse("questions.aaq_step1", locale="fi")
res = self.client.get(url_fi)
eq_(200, res.status_code)
self.assertEqual(200, res.status_code)
p = ProductFactory(slug="firefox")
url_fi = reverse("questions.aaq_step2", locale="fi", args=["desktop"])
url_en = reverse("questions.aaq_step2", locale="en-US", args=["desktop"])
res = self.client.get(url_fi)
eq_(302, res.status_code)
self.assertEqual(302, res.status_code)
assert res["location"].endswith(url_en)
locale = QuestionLocale.objects.get(locale="fi")
p.questions_locales.add(locale)
res = self.client.get(url_fi)
eq_(200, res.status_code)
self.assertEqual(200, res.status_code)
class AAQTests(TestCaseBase):
@ -283,7 +282,7 @@ class TestQuestionUpdates(TestCaseBase):
raise ValueError('req_type must be either "GET" or "POST"')
self.q = Question.objects.get(pk=self.q.id)
eq_(
self.assertEqual(
updated.strftime(self.date_format),
self.q.updated.strftime(self.date_format),
)
@ -325,7 +324,7 @@ class TroubleshootingParsingTests(TestCaseBase):
# This case should not raise an error.
response = get(self.client, "questions.details", args=[q.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_weird_list_troubleshooting_info(self):
"""Test the corner case in which 'modifiedPReferences' is in a
@ -335,7 +334,7 @@ class TroubleshootingParsingTests(TestCaseBase):
# This case should not raise an error.
response = get(self.client, "questions.details", args=[q.id])
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
def test_string_keys_troubleshooting(self):
"""Test something that looks like troubleshooting data, but
@ -392,7 +391,7 @@ class TestQuestionList(TestCaseBase):
"""Only questions for the current locale should be shown on the
questions front page for AAQ locales."""
eq_(Question.objects.count(), 0)
self.assertEqual(Question.objects.count(), 0)
p = ProductFactory(slug="firefox")
TopicFactory(title="Fix problems", slug="fix-problems", product=p)
@ -434,32 +433,32 @@ class TestQuestionReply(TestCaseBase):
reverse("questions.reply", args=[self.question.id]),
{"content": "The best reply evar!"},
)
eq_(res.status_code, 404)
self.assertEqual(res.status_code, 404)
def test_needs_info(self):
eq_(self.question.needs_info, False)
self.assertEqual(self.question.needs_info, False)
res = self.client.post(
reverse("questions.reply", args=[self.question.id]),
{"content": "More info please", "needsinfo": ""},
)
eq_(res.status_code, 302)
self.assertEqual(res.status_code, 302)
q = Question.objects.get(id=self.question.id)
eq_(q.needs_info, True)
self.assertEqual(q.needs_info, True)
def test_clear_needs_info(self):
self.question.set_needs_info()
eq_(self.question.needs_info, True)
self.assertEqual(self.question.needs_info, True)
res = self.client.post(
reverse("questions.reply", args=[self.question.id]),
{"content": "More info please", "clear_needsinfo": ""},
)
eq_(res.status_code, 302)
self.assertEqual(res.status_code, 302)
q = Question.objects.get(id=self.question.id)
eq_(q.needs_info, False)
self.assertEqual(q.needs_info, False)
class TestMarkingSolved(TestCaseBase):
@ -474,14 +473,14 @@ class TestMarkingSolved(TestCaseBase):
self.answer.save()
res = self.client.get(reverse("questions.solve", args=[self.question.id, self.answer.id]))
eq_(res.status_code, 404)
self.assertEqual(res.status_code, 404)
def test_cannot_mark_answers_on_spam_question(self):
self.question.is_spam = True
self.question.save()
res = self.client.get(reverse("questions.solve", args=[self.question.id, self.answer.id]))
eq_(res.status_code, 404)
self.assertEqual(res.status_code, 404)
class TestVoteAnswers(TestCaseBase):
@ -498,7 +497,7 @@ class TestVoteAnswers(TestCaseBase):
res = self.client.post(
reverse("questions.answer_vote", args=[self.question.id, self.answer.id])
)
eq_(res.status_code, 404)
self.assertEqual(res.status_code, 404)
def test_cannot_vote_for_answers_marked_spam(self):
self.answer.is_spam = True
@ -507,7 +506,7 @@ class TestVoteAnswers(TestCaseBase):
res = self.client.post(
reverse("questions.answer_vote", args=[self.question.id, self.answer.id])
)
eq_(res.status_code, 404)
self.assertEqual(res.status_code, 404)
class TestVoteQuestions(TestCaseBase):
@ -521,7 +520,7 @@ class TestVoteQuestions(TestCaseBase):
self.question.save()
res = self.client.post(reverse("questions.vote", args=[self.question.id]))
eq_(res.status_code, 404)
self.assertEqual(res.status_code, 404)
class TestQuestionDetails(TestCaseBase):
@ -533,14 +532,14 @@ class TestQuestionDetails(TestCaseBase):
self.question.save()
res = get(self.client, "questions.details", args=[self.question.id])
eq_(404, res.status_code)
self.assertEqual(404, res.status_code)
u = UserFactory()
add_permission(u, FlaggedObject, "can_moderate")
self.client.login(username=u.username, password="testpass")
res = get(self.client, "questions.details", args=[self.question.id])
eq_(200, res.status_code)
self.assertEqual(200, res.status_code)
class TestRateLimiting(TestCaseBase):
@ -554,15 +553,15 @@ class TestRateLimiting(TestCaseBase):
votes = QuestionVote.objects.filter(question=q).count()
res = self.client.post(url, HTTP_X_REQUESTED_WITH="XMLHttpRequest")
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)
data = json.loads(res.content)
eq_(data.get("ignored", False), ignored)
self.assertEqual(data.get("ignored", False), ignored)
if ignored:
eq_(QuestionVote.objects.filter(question=q).count(), votes)
self.assertEqual(QuestionVote.objects.filter(question=q).count(), votes)
else:
eq_(QuestionVote.objects.filter(question=q).count(), votes + 1)
self.assertEqual(QuestionVote.objects.filter(question=q).count(), votes + 1)
def _check_answer_vote(self, q, a, ignored):
"""Try and vote on `a`. If `ignored` is false, assert the
@ -572,15 +571,15 @@ class TestRateLimiting(TestCaseBase):
votes = AnswerVote.objects.filter(answer=a).count()
res = self.client.post(url, HTTP_X_REQUESTED_WITH="XMLHttpRequest")
eq_(res.status_code, 200)
self.assertEqual(res.status_code, 200)
data = json.loads(res.content)
eq_(data.get("ignored", False), ignored)
self.assertEqual(data.get("ignored", False), ignored)
if ignored:
eq_(AnswerVote.objects.filter(answer=a).count(), votes)
self.assertEqual(AnswerVote.objects.filter(answer=a).count(), votes)
else:
eq_(AnswerVote.objects.filter(answer=a).count(), votes + 1)
self.assertEqual(AnswerVote.objects.filter(answer=a).count(), votes + 1)
def test_question_vote_limit(self):
"""Test that an anonymous user's votes are ignored after 10
@ -668,7 +667,7 @@ class TestRateLimiting(TestCaseBase):
for i in range(7):
self.client.post(url, {"content": content})
eq_(4, Answer.objects.count())
self.assertEqual(4, Answer.objects.count())
class TestStats(Elastic7TestCase):
@ -690,7 +689,7 @@ class TestStats(Elastic7TestCase):
self.refresh()
response = self.client.get(reverse("questions.metrics"))
eq_(200, response.status_code)
self.assertEqual(200, response.status_code)
# If there's histogram data, this is probably good enough to
# denote its existence.
@ -731,24 +730,24 @@ class TestEditDetails(TestCaseBase):
u = UserFactory()
response = self._request(u, data=data)
eq_(403, response.status_code)
self.assertEqual(403, response.status_code)
response = self._request(data=data)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
def test_missing_data(self):
"""Test for missing data"""
data = {"product": self.product.id, "locale": self.question.locale}
response = self._request(data=data)
eq_(400, response.status_code)
self.assertEqual(400, response.status_code)
data = {"topic": self.topic.id, "locale": self.question.locale}
response = self._request(data=data)
eq_(400, response.status_code)
self.assertEqual(400, response.status_code)
data = {"product": self.product.id, "topic": self.topic.id}
response = self._request(data=data)
eq_(400, response.status_code)
self.assertEqual(400, response.status_code)
def test_bad_data(self):
"""Test for bad data"""
@ -758,11 +757,11 @@ class TestEditDetails(TestCaseBase):
"locale": self.question.locale,
}
response = self._request(data=data)
eq_(400, response.status_code)
self.assertEqual(400, response.status_code)
data = {"product": self.product.id, "topic": self.topic.id, "locale": "zu"}
response = self._request(data=data)
eq_(400, response.status_code)
self.assertEqual(400, response.status_code)
def test_change_topic(self):
"""Test changing the topic"""
@ -777,11 +776,11 @@ class TestEditDetails(TestCaseBase):
assert t_new.id != self.topic.id
response = self._request(data=data)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
q = Question.objects.get(id=self.question.id)
eq_(t_new.id, q.topic.id)
self.assertEqual(t_new.id, q.topic.id)
def test_change_product(self):
"""Test changing the product"""
@ -794,11 +793,11 @@ class TestEditDetails(TestCaseBase):
data = {"product": p_new.id, "topic": t_new.id, "locale": self.question.locale}
response = self._request(data=data)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
q = Question.objects.get(id=self.question.id)
eq_(p_new.id, q.product.id)
eq_(t_new.id, q.topic.id)
self.assertEqual(p_new.id, q.product.id)
self.assertEqual(t_new.id, q.topic.id)
def test_change_locale(self):
locale = "hu"
@ -809,7 +808,7 @@ class TestEditDetails(TestCaseBase):
data = {"product": self.product.id, "topic": self.topic.id, "locale": locale}
response = self._request(data=data)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
q = Question.objects.get(id=self.question.id)
eq_(q.locale, locale)
self.assertEqual(q.locale, locale)

Просмотреть файл

@ -1,5 +1,4 @@
from django.core.management import call_command
from nose.tools import eq_
from kitsune.questions.models import Question
from kitsune.questions.tests import QuestionFactory, QuestionVoteFactory, TestCaseBase
@ -10,16 +9,16 @@ class TestVotes(TestCaseBase):
def test_vote_updates_count(self):
q = QuestionFactory()
eq_(0, q.num_votes_past_week)
self.assertEqual(0, q.num_votes_past_week)
QuestionVoteFactory(question=q, anonymous_id="abc123")
q = Question.objects.get(id=q.id)
eq_(1, q.num_votes_past_week)
self.assertEqual(1, q.num_votes_past_week)
def test_cron_updates_counts(self):
q = QuestionFactory()
eq_(0, q.num_votes_past_week)
self.assertEqual(0, q.num_votes_past_week)
QuestionVoteFactory(question=q, anonymous_id="abc123")
@ -29,4 +28,4 @@ class TestVotes(TestCaseBase):
call_command("update_weekly_votes")
q = Question.objects.get(pk=q.pk)
eq_(1, q.num_votes_past_week)
self.assertEqual(1, q.num_votes_past_week)

Просмотреть файл

@ -1,4 +1,6 @@
from django.test.utils import override_settings
from kitsune.search.es7_utils import get_doc_types
from kitsune.sumo.tests import TestCase
@ -6,4 +8,8 @@ from kitsune.sumo.tests import TestCase
class Elastic7TestCase(TestCase):
"""Base class for Elastic Search 7 tests, providing some conveniences"""
...
def refresh(self):
"""Refresh ES7 indices."""
for doc_type in get_doc_types():
doc_type._index.refresh()

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
@ -9,7 +7,7 @@ class OpenSearchTestCase(TestCase):
def test_host(self):
response = self.client.get(reverse("search.plugin", locale="fr"))
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
# FIXME: This is silly. The better test would be to parse out
# the content and then go through and make sure all the urls
# were correct.
@ -17,11 +15,11 @@ class OpenSearchTestCase(TestCase):
def test_plugin_expires_and_mimetype(self):
response = self.client.get(reverse("search.plugin", locale="en-US"))
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
# Verify that it has the Expires: HTTP header
assert "expires" in response
# Verify the mimetype is correct
eq_(response["content-type"], "application/opensearchdescription+xml")
self.assertEqual(response["content-type"], "application/opensearchdescription+xml")
def test_plugin_uses_correct_locale(self):
response = self.client.get(reverse("search.plugin", locale="en-US"))

Просмотреть файл

@ -320,9 +320,9 @@
</footer>
{% if request.LANGUAGE_CODE %}
{% if settings.DEV or settings.TEST %}
<script src="{{ static('jsi18n/{lang}/djangojs.js'|f(lang=request.LANGUAGE_CODE|lower)) }}"></script>
<script src="{{ webpack_static('jsi18n/{lang}/djangojs.js'|f(lang=request.LANGUAGE_CODE|lower)) }}"></script>
{% else %}
<script src="{{ static('jsi18n/{lang}/djangojs-min.js'|f(lang=request.LANGUAGE_CODE|lower)) }}"></script>
<script src="{{ webpack_static('jsi18n/{lang}/djangojs-min.js'|f(lang=request.LANGUAGE_CODE|lower)) }}"></script>
{% endif %}
{% endif %}

Просмотреть файл

@ -1,11 +1,8 @@
# -*- coding: utf-8 -*-
import inspect
import os
import subprocess
import sys
from functools import wraps
from os import getenv
from smtplib import SMTPRecipientsRefused
from unittest import SkipTest
import factory.fuzzy
from django.conf import settings
@ -14,8 +11,6 @@ from django.test import TestCase as OriginalTestCase
from django.test.client import Client
from django.test.utils import override_settings
from django.utils.translation import trans_real
from nose import SkipTest # noqa
from nose.tools import eq_
from pyquery import PyQuery
from waffle.models import Flag
@ -60,7 +55,7 @@ class TestCase(OriginalTestCase):
def attrs_eq(received, **expected):
"""Compares received's attributes with expected's kwargs."""
for k, v in expected.items():
eq_(v, getattr(received, k))
assert v == getattr(received, k)
def starts_with(text, substring):
@ -110,7 +105,7 @@ class FuzzyUnicode(factory.fuzzy.FuzzyText):
"""A FuzzyText factory that contains at least one non-ASCII character."""
def __init__(self, prefix="", **kwargs):
prefix = "%sđ" % prefix
# prefix = "%sđ" % prefix
super(FuzzyUnicode, self).__init__(prefix=prefix, **kwargs)

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from django.conf import settings
from django.http import HttpResponse
from django.test.client import RequestFactory
@ -23,17 +21,17 @@ class TestAnonymousMiddleware(TestCase):
self.middleware.process_request(request)
# Make sure anonymous id isn't set then access it to generate it
eq_(False, request.anonymous.has_id)
self.assertEqual(False, request.anonymous.has_id)
anon_id = request.anonymous.anonymous_id
eq_(True, request.anonymous.has_id)
self.assertEqual(True, request.anonymous.has_id)
# Create and process the response
response = HttpResponse()
response = self.middleware.process_response(request, response)
# Make sure cookie is set with correct value
eq_(True, settings.ANONYMOUS_COOKIE_NAME in response.cookies)
eq_(anon_id, response.cookies[settings.ANONYMOUS_COOKIE_NAME].value)
self.assertEqual(True, settings.ANONYMOUS_COOKIE_NAME in response.cookies)
self.assertEqual(anon_id, response.cookies[settings.ANONYMOUS_COOKIE_NAME].value)
def test_cookie_not_set(self):
"""The anonymous cookie isn't set if it isn't created."""
@ -49,7 +47,7 @@ class TestAnonymousMiddleware(TestCase):
response = self.middleware.process_response(request, response)
# Make sure cookie was't set
eq_(False, settings.ANONYMOUS_COOKIE_NAME in response.cookies)
self.assertEqual(False, settings.ANONYMOUS_COOKIE_NAME in response.cookies)
def test_cookie_exists(self):
"""Anonymous cookie is already set.
@ -61,12 +59,12 @@ class TestAnonymousMiddleware(TestCase):
self.middleware.process_request(request)
# Make sure anonymous id is set to the right value
eq_(True, request.anonymous.has_id)
eq_(anon_id, request.anonymous.anonymous_id)
self.assertEqual(True, request.anonymous.has_id)
self.assertEqual(anon_id, request.anonymous.anonymous_id)
# Create and process the response
response = HttpResponse()
response = self.middleware.process_response(request, response)
# Make sure cookie was't set
eq_(False, settings.ANONYMOUS_COOKIE_NAME in response.cookies)
self.assertEqual(False, settings.ANONYMOUS_COOKIE_NAME in response.cookies)

Просмотреть файл

@ -1,25 +1,23 @@
import json
from nose.tools import eq_
from kitsune.sumo.urlresolvers import reverse
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
class TestLocalesAPIView(TestCase):
def test_basic(self):
url = reverse("sumo.locales_api")
response = self.client.get(url)
eq_(response.status_code, 200)
self.assertEqual(response.status_code, 200)
content = json.loads(response.content)
# Do some spot checks.
# NB: These checks will break when we change other parts of SUMO.
eq_(
self.assertEqual(
content["en-US"], {"name": "English", "localized_name": "English", "aaq_enabled": True}
)
eq_(
self.assertEqual(
content["fr"],
{"name": "French", "localized_name": "Fran\xe7ais", "aaq_enabled": False},
)

Просмотреть файл

@ -1,11 +1,9 @@
import pytz
from datetime import datetime
from unittest.mock import Mock
from nose.tools import eq_
import pytz
from django.test.client import RequestFactory
from django.test.utils import override_settings
from rest_framework import fields, serializers
from kitsune.sumo import api_utils
@ -24,7 +22,7 @@ class TestLanguageNegotiation(TestCase):
negotiater = api_utils.LocaleNegotiationMixin()
request = factory.get("/", HTTP_ACCEPT_LANGUAGE="es,en-US")
negotiater.request = request
eq_(negotiater.get_locale(), "es")
self.assertEqual(negotiater.get_locale(), "es")
class TestInequalityFilterBackend(TestCase):
@ -53,7 +51,7 @@ class TestInequalityFilterBackend(TestCase):
calls = self.queryset.method_calls
# Since both variables are in `filterset_fields`, they both get processed.
expected = [("filter", (), {"x__gte": 10}), ("filter", (), {"y__lt": 5})]
eq_(calls, expected)
self.assertEqual(calls, expected)
class TestDateTimeUTCField(TestCase):
@ -61,7 +59,7 @@ class TestDateTimeUTCField(TestCase):
field = api_utils.DateTimeUTCField()
as_pacific = pytz.timezone("US/Pacific").localize(datetime(2014, 11, 12, 13, 49, 59))
as_utc = field.to_representation(as_pacific)
eq_(as_utc, "2014-11-12T21:49:59Z")
self.assertEqual(as_utc, "2014-11-12T21:49:59Z")
# TODO: How can naive datetime conversion be tested?
@ -98,16 +96,16 @@ class TestPermissionMod(TestCase):
for case in cases:
allow, allow_obj, expected_val, expected_write_only = case
serializer = MockSerializer(instance=obj)
eq_(serializer.data.get("foo"), expected_val)
self.assertEqual(serializer.data.get("foo"), expected_val)
class TestJsonRenderer(TestCase):
def test_it_works(self):
expected = b'{"foo":"bar"}'
actual = api_utils.JSONRenderer().render({"foo": "bar"})
eq_(expected, actual)
self.assertEqual(expected, actual)
def test_it_escapes_bracket_slash(self):
expected = rb'{"xss":"<\/script>"}'
actual = api_utils.JSONRenderer().render({"xss": "</script>"})
eq_(expected, actual)
self.assertEqual(expected, actual)

Просмотреть файл

@ -4,7 +4,6 @@ from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.functional import lazy
from django.utils.translation import get_language
from nose.tools import eq_
from kitsune.sumo.email_utils import emails_with_users_and_watches, safe_translation
from kitsune.sumo.tests import TestCase
@ -39,7 +38,7 @@ class SafeTranslationTests(TestCase):
def setUp(self):
# These tests assume English is the fall back language. If it
# isn't we are gonna have a bad time.
eq_("en-US", settings.WIKI_DEFAULT_LANGUAGE)
self.assertEqual("en-US", settings.WIKI_DEFAULT_LANGUAGE)
@mock_gettext
def test_mocked_gettext(self):
@ -48,11 +47,11 @@ class SafeTranslationTests(TestCase):
from django.utils.translation import ugettext as _
with uselocale("en-US"):
eq_(_("Hello"), "Hello")
self.assertEqual(_("Hello"), "Hello")
with uselocale("fr"):
eq_(_("Hello"), "Bonjour")
self.assertEqual(_("Hello"), "Bonjour")
with uselocale("es"):
eq_(_("Hello"), "Hola")
self.assertEqual(_("Hello"), "Hola")
@mock_gettext
def test_safe_translation_noop(self):
@ -65,9 +64,9 @@ class SafeTranslationTests(TestCase):
return _("Hello")
# These should just work normally.
eq_(simple("en-US"), "Hello")
eq_(simple("fr"), "Bonjour")
eq_(simple("es"), "Hola")
self.assertEqual(simple("en-US"), "Hello")
self.assertEqual(simple("fr"), "Bonjour")
self.assertEqual(simple("es"), "Hola")
@mock_gettext
def test_safe_translation_bad_trans(self):
@ -83,9 +82,9 @@ class SafeTranslationTests(TestCase):
# French should come back as English, because it has a bad
# translation, but Spanish should come back in Spanish.
eq_(bad_trans("en-US"), "Hello Mike")
eq_(bad_trans("fr"), "Hello Mike")
eq_(bad_trans("es"), "Hola Mike")
self.assertEqual(bad_trans("en-US"), "Hello Mike")
self.assertEqual(bad_trans("fr"), "Hello Mike")
self.assertEqual(bad_trans("es"), "Hola Mike")
@mock_gettext
@patch("kitsune.sumo.email_utils.log")
@ -102,25 +101,25 @@ class SafeTranslationTests(TestCase):
# English and Spanish should not log anything. French should.
bad_trans("en-US")
bad_trans("es")
eq_(len(mocked_log.method_calls), 0)
self.assertEqual(len(mocked_log.method_calls), 0)
bad_trans("fr")
eq_(len(mocked_log.method_calls), 1)
self.assertEqual(len(mocked_log.method_calls), 1)
method_name, method_args, method_kwargs = mocked_log.method_calls[0]
eq_(method_name, "exception")
self.assertEqual(method_name, "exception")
assert "Bad translation" in method_args[0]
eq_(method_args[1], "fr")
self.assertEqual(method_args[1], "fr")
class UseLocaleTests(TestCase):
def test_uselocale(self):
"""Test that uselocale does what it says on the tin."""
with uselocale("en-US"):
eq_(get_language(), "en-us")
self.assertEqual(get_language(), "en-us")
with uselocale("de"):
eq_(get_language(), "de")
self.assertEqual(get_language(), "de")
with uselocale("fr"):
eq_(get_language(), "fr")
self.assertEqual(get_language(), "fr")
class PremailerTests(TestCase):

Просмотреть файл

@ -1,7 +1,5 @@
from django.core.exceptions import ValidationError
from nose.tools import eq_
from kitsune.sumo.form_fields import TypedMultipleChoiceField
from kitsune.sumo.tests import TestCase
@ -15,11 +13,11 @@ class TypedMultipleChoiceFieldTestCase(TestCase):
try:
callable(*args, **kwargs)
except error as e:
eq_(message, str(e))
self.assertEqual(message, str(e))
def test_typedmultiplechoicefield_71(self):
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
eq_([1], f.clean(["1"]))
self.assertEqual([1], f.clean(["1"]))
self.assertRaisesErrorWithMessage(
ValidationError,
"['Select a valid choice. 2 is not one of the available choices." "']",
@ -30,12 +28,12 @@ class TypedMultipleChoiceFieldTestCase(TestCase):
def test_typedmultiplechoicefield_72(self):
# Different coercion, same validation.
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float)
eq_([1.0], f.clean(["1"]))
self.assertEqual([1.0], f.clean(["1"]))
def test_typedmultiplechoicefield_73(self):
# This can also cause weirdness: bool(-1) == True
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool)
eq_([True], f.clean(["-1"]))
self.assertEqual([True], f.clean(["-1"]))
def test_typedmultiplechoicefield_74(self):
# Even more weirdness: if you have a valid choice but your coercion
@ -56,7 +54,7 @@ class TypedMultipleChoiceFieldTestCase(TestCase):
def test_typedmultiplechoicefield_75(self):
# Non-required fields aren't required
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False)
eq_([], f.clean([]))
self.assertEqual([], f.clean([]))
def test_typedmultiplechoicefield_76(self):
# If you want cleaning an empty value to return a different type,
@ -64,9 +62,9 @@ class TypedMultipleChoiceFieldTestCase(TestCase):
f = TypedMultipleChoiceField(
choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None
)
eq_(None, f.clean([]))
self.assertEqual(None, f.clean([]))
def test_coerce_only(self):
"""No validation error raised in this case."""
f = TypedMultipleChoiceField(choices=[(1, "+1")], coerce=int, coerce_only=True)
eq_([], f.clean(["2"]))
self.assertEqual([], f.clean(["2"]))

Просмотреть файл

@ -1,6 +1,4 @@
from django import forms
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.sumo.tests import TestCase
@ -25,7 +23,7 @@ class TestFields(TestCase):
def _attr_eq(self, field, attr, value):
doc = pq(str(self.f[field]))
eq_(value, doc.attr(attr))
self.assertEqual(value, doc.attr(attr))
def test_date_field(self):
self._attr_eq("date", "type", "date")

Просмотреть файл

@ -1,7 +1,5 @@
from datetime import date
from unittest.mock import patch
from nose.tools import eq_
from kitsune.sumo import googleanalytics
from kitsune.sumo.tests import TestCase
@ -19,8 +17,8 @@ class GoogleAnalyticsTests(TestCase):
visits = googleanalytics.visitors(date(2013, 1, 16), date(2013, 1, 16))
eq_(1, len(visits))
eq_(382719, visits["2013-01-16"])
self.assertEqual(1, len(visits))
self.assertEqual(382719, visits["2013-01-16"])
@patch.object(googleanalytics, "_build_request")
def test_visitors_by_locale(self, _build_request):
@ -30,9 +28,9 @@ class GoogleAnalyticsTests(TestCase):
visits = googleanalytics.visitors_by_locale(date(2013, 1, 16), date(2013, 1, 16))
eq_(58, len(visits))
eq_(221447, visits["en-US"])
eq_(24432, visits["es"])
self.assertEqual(58, len(visits))
self.assertEqual(221447, visits["en-US"])
self.assertEqual(24432, visits["es"])
@patch.object(googleanalytics, "_build_request")
def test_pageviews_by_document(self, _build_request):
@ -47,12 +45,12 @@ class GoogleAnalyticsTests(TestCase):
pageviews = googleanalytics.pageviews_by_document(date(2013, 1, 16), date(2013, 1, 16))
eq_(5, len(pageviews))
eq_(1, pageviews[documents[0].pk])
eq_(2, pageviews[documents[1].pk])
eq_(10, pageviews[documents[2].pk])
eq_(39, pageviews[documents[3].pk])
eq_(46, pageviews[documents[4].pk])
self.assertEqual(5, len(pageviews))
self.assertEqual(1, pageviews[documents[0].pk])
self.assertEqual(2, pageviews[documents[1].pk])
self.assertEqual(10, pageviews[documents[2].pk])
self.assertEqual(39, pageviews[documents[3].pk])
self.assertEqual(46, pageviews[documents[4].pk])
@patch.object(googleanalytics, "_build_request")
def test_pageviews_by_question(self, _build_request):
@ -62,10 +60,10 @@ class GoogleAnalyticsTests(TestCase):
pageviews = googleanalytics.pageviews_by_question(date(2013, 1, 16), date(2013, 1, 16))
eq_(3, len(pageviews))
eq_(3, pageviews[1])
eq_(2, pageviews[2])
eq_(11, pageviews[3])
self.assertEqual(3, len(pageviews))
self.assertEqual(3, pageviews[1])
self.assertEqual(2, pageviews[2])
self.assertEqual(11, pageviews[3])
@patch.object(googleanalytics, "_build_request")
def test_search_ctr(self, _build_request):
@ -75,8 +73,8 @@ class GoogleAnalyticsTests(TestCase):
ctr = googleanalytics.search_ctr(date(2013, 6, 6), date(2013, 6, 6))
eq_(1, len(ctr))
eq_(74.88925980111263, ctr["2013-06-06"])
self.assertEqual(1, len(ctr))
self.assertEqual(74.88925980111263, ctr["2013-06-06"])
VISITORS_RESPONSE = {

Просмотреть файл

@ -4,11 +4,8 @@ from django import http
from django.core.exceptions import PermissionDenied
from django.test import RequestFactory, TestCase
from nose.tools import eq_
from kitsune.sumo.decorators import json_view
rf = RequestFactory()
JSON = "application/json"
@ -27,9 +24,9 @@ class JsonViewTests(TestCase):
return data
res = temp(rf.get("/"))
eq_(200, res.status_code)
eq_(expect, res.content)
eq_(JSON, res["content-type"])
self.assertEqual(200, res.status_code)
self.assertEqual(expect, res.content)
self.assertEqual(JSON, res["content-type"])
def test_list(self):
data = ["foo", "bar", "baz"]
@ -40,9 +37,9 @@ class JsonViewTests(TestCase):
return data
res = temp(rf.get("/"))
eq_(200, res.status_code)
eq_(expect, res.content)
eq_(JSON, res["content-type"])
self.assertEqual(200, res.status_code)
self.assertEqual(expect, res.content)
self.assertEqual(JSON, res["content-type"])
def test_404(self):
@json_view
@ -50,11 +47,11 @@ class JsonViewTests(TestCase):
raise http.Http404("foo")
res = temp(rf.get("/"))
eq_(404, res.status_code)
eq_(JSON, res["content-type"])
self.assertEqual(404, res.status_code)
self.assertEqual(JSON, res["content-type"])
data = json.loads(res.content)
eq_(404, data["error"])
eq_("foo", data["message"])
self.assertEqual(404, data["error"])
self.assertEqual("foo", data["message"])
def test_permission(self):
@json_view
@ -62,11 +59,11 @@ class JsonViewTests(TestCase):
raise PermissionDenied("bar")
res = temp(rf.get("/"))
eq_(403, res.status_code)
eq_(JSON, res["content-type"])
self.assertEqual(403, res.status_code)
self.assertEqual(JSON, res["content-type"])
data = json.loads(res.content)
eq_(403, data["error"])
eq_("bar", data["message"])
self.assertEqual(403, data["error"])
self.assertEqual("bar", data["message"])
def test_server_error(self):
@json_view
@ -74,8 +71,8 @@ class JsonViewTests(TestCase):
raise TypeError("fail")
res = temp(rf.get("/"))
eq_(500, res.status_code)
eq_(JSON, res["content-type"])
self.assertEqual(500, res.status_code)
self.assertEqual(JSON, res["content-type"])
data = json.loads(res.content)
eq_(500, data["error"])
eq_("fail", data["message"])
self.assertEqual(500, data["error"])
self.assertEqual("fail", data["message"])

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from django.http import HttpResponse
from django.test.client import RequestFactory
@ -28,7 +26,7 @@ def test_jsonp_is_valid():
("var x=", False),
]
for funcname, expected in tests:
eq_(jsonp_is_valid(funcname), expected)
TestCase().assertEqual(jsonp_is_valid(funcname), expected)
def random_view_fun(request, *args, **kwargs):
@ -46,63 +44,64 @@ class TestMarkupJson(TestCase):
# the request and response after processing the request.
req = self.factory.get("/")
resp = jsonified_fun(req)
eq_(req.IS_JSON, False)
eq_(resp.status_code, 200)
self.assertEqual(req.IS_JSON, False)
self.assertEqual(resp.status_code, 200)
def test_is_json_false_wrong_format(self):
req = self.factory.get("/", {"format": "html"})
resp = jsonified_fun(req)
eq_(req.IS_JSON, False)
eq_(resp.status_code, 200)
self.assertEqual(req.IS_JSON, False)
self.assertEqual(resp.status_code, 200)
def test_is_json_true(self):
req = self.factory.get("/", {"format": "json"})
resp = jsonified_fun(req)
eq_(req.IS_JSON, True)
eq_(resp.status_code, 200)
self.assertEqual(req.IS_JSON, True)
self.assertEqual(resp.status_code, 200)
def test_json_callback_not_is_json(self):
req = self.factory.get("/")
resp = jsonified_fun(req)
eq_(req.IS_JSON, False)
eq_(req.JSON_CALLBACK, "")
eq_(resp.status_code, 200)
self.assertEqual(req.IS_JSON, False)
self.assertEqual(req.JSON_CALLBACK, "")
self.assertEqual(resp.status_code, 200)
def test_json_callback_valid(self):
req = self.factory.get("/", {"format": "json", "callback": "callback"})
resp = jsonified_fun(req)
eq_(req.IS_JSON, True)
eq_(req.JSON_CALLBACK, "callback")
eq_(resp.status_code, 200)
self.assertEqual(req.IS_JSON, True)
self.assertEqual(req.JSON_CALLBACK, "callback")
self.assertEqual(resp.status_code, 200)
def test_json_callback_invalid(self):
req = self.factory.get("/", {"format": "json", "callback": '">'})
resp = jsonified_fun(req)
eq_(resp.status_code, 400)
eq_(resp.content, b'{"error": "Invalid callback function."}')
self.assertEqual(resp.status_code, 400)
self.assertEqual(resp.content, b'{"error": "Invalid callback function."}')
def test_content_type_not_json(self):
req = self.factory.get("/")
resp = jsonified_fun(req)
eq_(req.IS_JSON, False)
eq_(req.CONTENT_TYPE, "text/html")
eq_(resp.status_code, 200)
self.assertEqual(req.IS_JSON, False)
self.assertEqual(req.CONTENT_TYPE, "text/html")
self.assertEqual(resp.status_code, 200)
def test_content_type_json(self):
req = self.factory.get("/", {"format": "json"})
resp = jsonified_fun(req)
eq_(req.IS_JSON, True)
eq_(req.CONTENT_TYPE, "application/json")
eq_(resp.status_code, 200)
self.assertEqual(req.IS_JSON, True)
self.assertEqual(req.CONTENT_TYPE, "application/json")
self.assertEqual(resp.status_code, 200)
def test_content_type_jsonp(self):
req = self.factory.get("/", {"format": "json", "callback": "callback"})
resp = jsonified_fun(req)
eq_(req.IS_JSON, True)
eq_(req.CONTENT_TYPE, "application/x-javascript")
eq_(resp.status_code, 200)
self.assertEqual(req.IS_JSON, True)
self.assertEqual(req.CONTENT_TYPE, "application/x-javascript")
self.assertEqual(resp.status_code, 200)
def test_template_json():
eq_(template_json([]), "[]")
eq_(type(template_json([])), str)
tc = TestCase()
tc.assertEqual(template_json([]), "[]")
tc.assertEqual(type(template_json([])), str)

Просмотреть файл

@ -1,8 +1,6 @@
from django.conf import settings
from django.test import override_settings
from nose.tools import eq_
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import get_best_language, get_non_supported
from kitsune.users.tests import UserFactory
@ -55,30 +53,30 @@ class TestLocaleMiddleware(TestCase):
class BestLanguageTests(TestCase):
def test_english_only(self):
best = get_best_language("en-us, en;q=0.8")
eq_("en-US", best)
self.assertEqual("en-US", best)
def test_en_GB(self):
"""Stick with English if you can."""
best = get_best_language("en-gb, fr;q=0.8")
eq_("en-US", best)
self.assertEqual("en-US", best)
def test_not_worst_choice(self):
"""Try not to fall back to 'es' here."""
best = get_best_language("en-gb, en;q=0.8, fr-fr;q=0.6, es;q=0.2")
eq_("en-US", best)
self.assertEqual("en-US", best)
def test_fr_FR(self):
best = get_best_language("fr-FR, es;q=0.8")
eq_("fr", best)
self.assertEqual("fr", best)
def test_non_existent(self):
best = get_best_language("xy-YY, xy;q=0.8")
eq_(False, best)
self.assertEqual(False, best)
def test_prefix_matching(self):
"""en-US is a better match for en-gb, es;q=0.2 than es."""
best = get_best_language("en-gb, es;q=0.2")
eq_("en-US", best)
self.assertEqual("en-US", best)
class PreferredLanguageTests(TestCase):
@ -124,10 +122,10 @@ class PreferredLanguageTests(TestCase):
class NonSupportedTests(TestCase):
@override_settings(NON_SUPPORTED_LOCALES={"nn-NO": "no", "xx": None})
def test_get_non_supported(self):
eq_("no", get_non_supported("nn-NO"))
eq_("no", get_non_supported("nn-no"))
eq_(settings.LANGUAGE_CODE, get_non_supported("xx"))
eq_(None, get_non_supported("yy"))
self.assertEqual("no", get_non_supported("nn-NO"))
self.assertEqual("no", get_non_supported("nn-no"))
self.assertEqual(settings.LANGUAGE_CODE, get_non_supported("xx"))
self.assertEqual(None, get_non_supported("yy"))
@override_settings(NON_SUPPORTED_LOCALES={"nn-NO": "no", "xy": None})
def test_middleware(self):

Просмотреть файл

@ -1,7 +1,6 @@
from django.http import HttpResponse, HttpResponsePermanentRedirect
from django.test import override_settings
from django.test.client import RequestFactory
from nose.tools import eq_
from kitsune.sumo.middleware import (
CacheHeadersMiddleware,
@ -79,15 +78,15 @@ class CacheHeadersMiddlewareTestCase(TestCase):
class TrailingSlashMiddlewareTestCase(TestCase):
def test_no_trailing_slash(self):
response = self.client.get("/en-US/ohnoez")
eq_(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_404_trailing_slash(self):
response = self.client.get("/en-US/ohnoez/")
eq_(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_remove_trailing_slash(self):
response = self.client.get("/en-US/home/?xxx=%C3%83")
eq_(response.status_code, 301)
self.assertEqual(response.status_code, 301)
assert response["Location"].endswith("/en-US/home?xxx=%C3%83")
@ -103,19 +102,19 @@ class PlusToSpaceTestCase(TestCase):
del request.META["QUERY_STRING"]
response = self.ptsm.process_request(request)
assert isinstance(response, HttpResponsePermanentRedirect)
eq_("/url%20with%20plus", response["location"])
self.assertEqual("/url%20with%20plus", response["location"])
def test_query_string(self):
"""Query strings should be maintained."""
request = self.rf.get("/pa+th", {"a": "b"})
response = self.ptsm.process_request(request)
eq_("/pa%20th?a=b", response["location"])
self.assertEqual("/pa%20th?a=b", response["location"])
def test_query_string_unaffected(self):
"""Pluses in query strings are not affected."""
request = self.rf.get("/pa+th?var=a+b")
response = self.ptsm.process_request(request)
eq_("/pa%20th?var=a+b", response["location"])
self.assertEqual("/pa%20th?var=a+b", response["location"])
def test_pass_through(self):
"""URLs without a + should be left alone."""
@ -127,7 +126,7 @@ class PlusToSpaceTestCase(TestCase):
request = self.rf.get("/pa+th", {"a": "b"})
request.LANGUAGE_CODE = "ru"
response = self.ptsm.process_request(request)
eq_("/ru/pa%20th?a=b", response["location"])
self.assertEqual("/ru/pa%20th?a=b", response["location"])
def test_smart_query_string(self):
"""The request QUERY_STRING might not be unicode."""
@ -135,4 +134,4 @@ class PlusToSpaceTestCase(TestCase):
request.LANGUAGE_CODE = "ja"
request.META["QUERY_STRING"] = "s=%E3%82%A2"
response = self.ptsm.process_request(request)
eq_("/ja/pa%20th?s=%E3%82%A2", response["location"])
self.assertEqual("/ja/pa%20th?s=%E3%82%A2", response["location"])

Просмотреть файл

@ -1,10 +1,8 @@
import pyquery
from django.test.client import RequestFactory
import pyquery
from nose.tools import eq_, raises
from kitsune.sumo.templatetags.jinja_helpers import paginator
from kitsune.sumo.paginator import EmptyPage, PageNotAnInteger
from kitsune.sumo.templatetags.jinja_helpers import paginator
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
from kitsune.sumo.utils import paginate, simple_paginate
@ -16,7 +14,9 @@ def test_paginated_url():
request = RequestFactory().get(url)
queryset = [{}, {}]
paginated = paginate(request, queryset)
eq_(paginated.url, request.build_absolute_uri(request.path) + "?q=bookmarks")
TestCase().assertEqual(
paginated.url, request.build_absolute_uri(request.path) + "?q=bookmarks"
)
def test_invalid_page_param():
@ -24,18 +24,19 @@ def test_invalid_page_param():
request = RequestFactory().get(url)
queryset = list(range(100))
paginated = paginate(request, queryset)
eq_(paginated.url, request.build_absolute_uri(request.path) + "?")
TestCase().assertEqual(paginated.url, request.build_absolute_uri(request.path) + "?")
def test_paginator_filter():
tc = TestCase()
# Correct number of <li>s on page 1.
url = reverse("search")
request = RequestFactory().get(url)
pager = paginate(request, list(range(100)), per_page=9)
html = paginator(pager)
doc = pyquery.PyQuery(html)
eq_(11, len(doc("li")))
tc.assertEqual(11, len(doc("li")))
# Correct number of <li>s in the middle.
url = "%s?%s" % (reverse("search"), "page=10")
@ -43,7 +44,7 @@ def test_paginator_filter():
pager = paginate(request, list(range(200)), per_page=10)
html = paginator(pager)
doc = pyquery.PyQuery(html)
eq_(13, len(doc("li")))
tc.assertEqual(13, len(doc("li")))
class SimplePaginatorTestCase(TestCase):
@ -55,14 +56,14 @@ class SimplePaginatorTestCase(TestCase):
request = self.rf.get("/questions")
queryset = [{}, {}]
page = simple_paginate(request, queryset, per_page=2)
eq_(1, page.number)
self.assertEqual(1, page.number)
def test_page_1_without_next(self):
"""Test page=1, doesn't have next page."""
request = self.rf.get("/questions?page=1")
queryset = [{}, {}]
page = simple_paginate(request, queryset, per_page=2)
eq_(1, page.number)
self.assertEqual(1, page.number)
assert not page.has_previous()
assert not page.has_next()
@ -71,7 +72,7 @@ class SimplePaginatorTestCase(TestCase):
request = self.rf.get("/questions?page=1")
queryset = [{}, {}, {}]
page = simple_paginate(request, queryset, per_page=2)
eq_(1, page.number)
self.assertEqual(1, page.number)
assert not page.has_previous()
assert page.has_next()
@ -80,20 +81,20 @@ class SimplePaginatorTestCase(TestCase):
request = self.rf.get("/questions?page=2")
queryset = [{}, {}, {}]
page = simple_paginate(request, queryset, per_page=2)
eq_(2, page.number)
self.assertEqual(2, page.number)
assert page.has_previous()
assert not page.has_next()
@raises(EmptyPage)
def test_page_2_empty(self):
"""Test page=1, has next page."""
request = self.rf.get("/questions?page=2")
queryset = [{}, {}]
simple_paginate(request, queryset, per_page=2)
with self.assertRaises(EmptyPage):
simple_paginate(request, queryset, per_page=2)
@raises(PageNotAnInteger)
def test_page_isnt_an_int(self):
"""Test page=1, has next page."""
request = self.rf.get("/questions?page=foo")
queryset = [{}, {}]
simple_paginate(request, queryset, per_page=2)
with self.assertRaises(PageNotAnInteger):
simple_paginate(request, queryset, per_page=2)

Просмотреть файл

@ -1,22 +1,20 @@
from functools import partial
from django.conf import settings
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.gallery.tests import ImageFactory
from kitsune.sumo.parser import (
WikiParser,
build_hook_params,
_get_wiki_link,
get_object_fallback,
IMAGE_PARAMS,
IMAGE_PARAM_VALUES,
IMAGE_PARAMS,
WikiParser,
_get_wiki_link,
build_hook_params,
get_object_fallback,
)
from kitsune.sumo.tests import TestCase
from kitsune.wiki.models import Document
from kitsune.wiki.tests import DocumentFactory, ApprovedRevisionFactory
from kitsune.wiki.tests import ApprovedRevisionFactory, DocumentFactory
def pq_link(p, text):
@ -48,14 +46,14 @@ class GetObjectFallbackTests(TestCase):
"""get_object_fallback returns message when no objects."""
# English does not exist
obj = get_object_fallback(Document, "A doc", "en-US", "!")
eq_("!", obj)
self.assertEqual("!", obj)
def test_english(self):
# Create the English document
d = DocumentFactory(title="A doc")
# Now it exists
obj = get_object_fallback(Document, "A doc", "en-US", "!")
eq_(d, obj)
self.assertEqual(d, obj)
def test_from_french(self):
# Create the English document
@ -63,7 +61,7 @@ class GetObjectFallbackTests(TestCase):
d.save()
# Returns English document for French
obj = get_object_fallback(Document, "A doc", "fr", "!")
eq_(d, obj)
self.assertEqual(d, obj)
def test_french(self):
# Create English parent document
@ -73,12 +71,12 @@ class GetObjectFallbackTests(TestCase):
# Create the French document
fr_d = DocumentFactory(parent=en_d, title="A doc", locale="fr")
obj = get_object_fallback(Document, "A doc", "fr", "!")
eq_(fr_d, obj)
self.assertEqual(fr_d, obj)
# Also works when English exists
DocumentFactory(title="A doc")
obj = get_object_fallback(Document, "A doc", "fr", "!")
eq_(fr_d, obj)
self.assertEqual(fr_d, obj)
def test_translated(self):
"""If a localization of the English fallback exists, use it."""
@ -90,12 +88,12 @@ class GetObjectFallbackTests(TestCase):
# Without an approved revision, the en-US doc should be returned.
obj = get_object_fallback(Document, "A doc", "fr")
eq_(en_d, obj)
self.assertEqual(en_d, obj)
# Approve a revision, then fr doc should be returned.
ApprovedRevisionFactory(document=fr_d)
obj = get_object_fallback(Document, "A doc", "fr")
eq_(fr_d, obj)
self.assertEqual(fr_d, obj)
def test_redirect(self):
"""Assert get_object_fallback follows wiki redirects."""
@ -105,7 +103,7 @@ class GetObjectFallbackTests(TestCase):
)
ApprovedRevisionFactory(document__title="redirect", content="REDIRECT [[target]]")
eq_(
self.assertEqual(
translated_target_rev.document,
get_object_fallback(Document, "redirect", "de"),
)
@ -122,7 +120,7 @@ class GetObjectFallbackTests(TestCase):
redirect_rev = ApprovedRevisionFactory(
document__title="redirect", content="REDIRECT [[target]]"
)
eq_(
self.assertEqual(
redirect_rev.document,
get_object_fallback(Document, "redirect", redirect_rev.document.locale),
)
@ -135,26 +133,26 @@ class TestWikiParser(TestCase):
def test_image_params_page(self):
"""build_hook_params handles wiki pages."""
_, params = build_hook_params_default("t|page=Installing Firefox")
eq_("/en-US/kb/installing-firefox", params["link"])
self.assertEqual("/en-US/kb/installing-firefox", params["link"])
assert params["found"]
def test_image_params_link(self):
"""_build_image_params handles external links."""
_, params = build_hook_params_default("t|link=http://example.com")
eq_("http://example.com", params["link"])
self.assertEqual("http://example.com", params["link"])
def test_image_params_page_link(self):
"""_build_image_params - wiki page overrides link."""
text = "t|page=Installing Firefox|link=http://example.com"
_, params = build_hook_params_default(text)
eq_("/en-US/kb/installing-firefox", params["link"])
self.assertEqual("/en-US/kb/installing-firefox", params["link"])
def test_image_params_align(self):
"""Align valid options."""
align_vals = ("none", "left", "center", "right")
for align in align_vals:
_, params = build_hook_params_default("test.jpg|align=" + align)
eq_(align, params["align"])
self.assertEqual(align, params["align"])
def test_image_params_align_invalid(self):
"""Align invalid options."""
@ -175,7 +173,7 @@ class TestWikiParser(TestCase):
)
for valign in valign_vals:
_, params = build_hook_params_default("title|valign=" + valign)
eq_(valign, params["valign"])
self.assertEqual(valign, params["valign"])
def test_image_params_valign_invalid(self):
"""Vertical align invalid options."""
@ -185,7 +183,7 @@ class TestWikiParser(TestCase):
def test_image_params_alt(self):
"""Image alt override."""
_, params = build_hook_params_default("t|alt=some alternative text")
eq_("some alternative text", params["alt"])
self.assertEqual("some alternative text", params["alt"])
def test_image_params_frame(self):
"""Framed image."""
@ -195,12 +193,12 @@ class TestWikiParser(TestCase):
def test_image_params_width_height(self):
"""Image width."""
_, params = build_hook_params_default("t|width=10|height=20")
eq_("10", params["width"])
eq_("20", params["height"])
self.assertEqual("10", params["width"])
self.assertEqual("20", params["height"])
def test_get_wiki_link(self):
"""Wiki links are properly built for existing pages."""
eq_(
self.assertEqual(
{
"found": True,
"url": "/en-US/kb/installing-firefox",
@ -211,7 +209,7 @@ class TestWikiParser(TestCase):
def test_showfor(self):
"""<showfor> tags should be escaped, not obeyed."""
eq_(
self.assertEqual(
"<p>&lt;showfor&gt;smoo&lt;/showfor&gt;</p>",
self.p.parse("<showfor>smoo</showfor>").replace("\n", ""),
)
@ -232,7 +230,7 @@ class TestWikiParser(TestCase):
def test_iframe_in_markup(self):
"""Verify iframe in wiki markup is escaped."""
doc = pq(self.p.parse('<iframe src="http://example.com"></iframe>'))
eq_(0, len(doc("iframe")))
self.assertEqual(0, len(doc("iframe")))
def test_iframe_hell_bug_898769(self):
"""Verify fix for bug 898769."""
@ -242,7 +240,7 @@ class TestWikiParser(TestCase):
<svg/onload=alert(1)"""
eq_(
self.assertEqual(
'<p>&lt;iframe src="" \\="" onload="prompt(1)" &lt;="" p=""'
"&gt;&lt;p&gt;&lt;iframe/onreadystatechange="
"alert(/@blinkms/)\n&lt;/p&gt;&lt;p&gt;&lt;"
@ -277,7 +275,7 @@ class TestWikiParser(TestCase):
("<IMG SRC=\"javascript:alert('XSS');\">", "<p><img>\n</p>"),
)
for content, expected in testdata:
eq_(expected, self.p.parse(content))
self.assertEqual(expected, self.p.parse(content))
class TestWikiInternalLinks(TestCase):
@ -287,13 +285,13 @@ class TestWikiInternalLinks(TestCase):
def test_simple(self):
"""Simple internal link markup."""
link = pq_link(self.p, "[[Installing Firefox]]")
eq_("/en-US/kb/installing-firefox", link.attr("href"))
eq_("Installing Firefox", link.text())
self.assertEqual("/en-US/kb/installing-firefox", link.attr("href"))
self.assertEqual("Installing Firefox", link.text())
assert not link.hasClass("new")
def test_simple_markup(self):
text = "[[Installing Firefox]]"
eq_(
self.assertEqual(
'<p><a href="/en-US/kb/installing-firefox">' + "Installing Firefox</a></p>",
self.p.parse(text).replace("\n", ""),
)
@ -301,49 +299,49 @@ class TestWikiInternalLinks(TestCase):
def test_link_hash(self):
"""Internal link with hash."""
link = pq_link(self.p, "[[Installing Firefox#section name]]")
eq_("/en-US/kb/installing-firefox#section_name", link.attr("href"))
eq_("Installing Firefox", link.text())
self.assertEqual("/en-US/kb/installing-firefox#section_name", link.attr("href"))
self.assertEqual("Installing Firefox", link.text())
def test_link_hash_text(self):
"""Internal link with hash and text."""
link = pq_link(self.p, "[[Installing Firefox#section name|section]]")
eq_("/en-US/kb/installing-firefox#section_name", link.attr("href"))
eq_("section", link.text())
self.assertEqual("/en-US/kb/installing-firefox#section_name", link.attr("href"))
self.assertEqual("section", link.text())
def test_hash_only(self):
"""Internal hash only."""
link = pq_link(self.p, "[[#section 3]]")
eq_("#section_3", link.attr("href"))
eq_("#section 3", link.text())
self.assertEqual("#section_3", link.attr("href"))
self.assertEqual("#section 3", link.text())
def test_link_name(self):
"""Internal link with name."""
link = pq_link(self.p, "[[Installing Firefox|this name]]")
eq_("/en-US/kb/installing-firefox", link.attr("href"))
eq_("this name", link.text())
self.assertEqual("/en-US/kb/installing-firefox", link.attr("href"))
self.assertEqual("this name", link.text())
def test_link_with_extra_pipe(self):
link = pq_link(self.p, "[[Installing Firefox|with|pipe]]")
eq_("/en-US/kb/installing-firefox", link.attr("href"))
eq_("with|pipe", link.text())
self.assertEqual("/en-US/kb/installing-firefox", link.attr("href"))
self.assertEqual("with|pipe", link.text())
def test_hash_name(self):
"""Internal hash with name."""
link = pq_link(self.p, "[[#section 3|this name]]")
eq_("#section_3", link.attr("href"))
eq_("this name", link.text())
self.assertEqual("#section_3", link.attr("href"))
self.assertEqual("this name", link.text())
assert not link.hasClass("new")
def test_link_hash_name(self):
"""Internal link with hash and name."""
link = pq_link(self.p, "[[Installing Firefox#section 3|this name]]")
eq_("/en-US/kb/installing-firefox#section_3", link.attr("href"))
eq_("this name", link.text())
self.assertEqual("/en-US/kb/installing-firefox#section_3", link.attr("href"))
self.assertEqual("this name", link.text())
def test_link_hash_name_markup(self):
"""Internal link with hash and name."""
text = "[[Installing Firefox#section 3|this name]]"
eq_(
self.assertEqual(
'<p><a href="/en-US/kb/installing-firefox#section_3">this name</a>\n</p>',
self.p.parse(text),
)
@ -352,14 +350,14 @@ class TestWikiInternalLinks(TestCase):
"""Simple link for inexistent page."""
link = pq_link(self.p, "[[A new page]]")
assert link.hasClass("new")
eq_("/en-US/kb/new?title=A+new+page", link.attr("href"))
eq_("A new page", link.text())
self.assertEqual("/en-US/kb/new?title=A+new+page", link.attr("href"))
self.assertEqual("A new page", link.text())
def test_link_edit_hash_name(self):
"""Internal link for inexistent page with hash and name."""
link = pq_link(self.p, "[[A new page#section 3|this name]]")
eq_("/en-US/kb/new?title=A+new+page#section_3", link.attr("href"))
eq_("this name", link.text())
self.assertEqual("/en-US/kb/new?title=A+new+page#section_3", link.attr("href"))
self.assertEqual("this name", link.text())
def test_link_with_localization(self):
"""A link to an English doc with a local translation."""
@ -371,14 +369,14 @@ class TestWikiInternalLinks(TestCase):
# 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())
self.assertEqual("/fr/kb/a-doc", link.find("a").attr("href"))
self.assertEqual("A doc", link.find("a").text())
# Approve a revision. Now link should go to fr doc.
ApprovedRevisionFactory(document=fr_d)
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())
self.assertEqual("/fr/kb/une-doc", link.find("a").attr("href"))
self.assertEqual("Une doc", link.find("a").text())
class TestWikiImageTags(TestCase):
@ -392,19 +390,19 @@ class TestWikiImageTags(TestCase):
def test_empty(self):
"""Empty image tag markup does not change."""
img = pq_img(self.p, "[[Image:]]", "p")
eq_('The image "" does not exist.', img.text())
self.assertEqual('The image "" does not exist.', img.text())
def test_simple(self):
"""Simple image tag markup."""
img = pq_img(self.p, "[[Image:test.jpg]]", "img")
eq_("test.jpg", img.attr("alt"))
eq_(self.img.file.url, img.attr("src"))
self.assertEqual("test.jpg", img.attr("alt"))
self.assertEqual(self.img.file.url, img.attr("src"))
def test_simple_fallback(self):
"""Fallback to English if current locale doesn't have the image."""
img = pq_img(self.p, "[[Image:test.jpg]]", selector="img", locale="ja")
eq_("test.jpg", img.attr("alt"))
eq_(self.img.file.url, img.attr("src"))
self.assertEqual("test.jpg", img.attr("alt"))
self.assertEqual(self.img.file.url, img.attr("src"))
def test_full_fallback(self):
"""Find current locale's image, not the English one."""
@ -412,8 +410,8 @@ class TestWikiImageTags(TestCase):
self.img.locale = "ja"
self.img.save()
img = pq_img(self.p, "[[Image:test.jpg]]", selector="img", locale="ja")
eq_("test.jpg", img.attr("alt"))
eq_(self.img.file.url, img.attr("src"))
self.assertEqual("test.jpg", img.attr("alt"))
self.assertEqual(self.img.file.url, img.attr("src"))
# then, create an English version
en_img = ImageFactory(title="test.jpg", locale="en-US")
@ -422,15 +420,15 @@ class TestWikiImageTags(TestCase):
# make sure there is no fallback
img = pq_img(self.p, "[[Image:test.jpg]]", selector="img", locale="ja")
eq_("test.jpg", img.attr("alt"))
eq_(self.img.file.url, img.attr("src"))
self.assertEqual("test.jpg", img.attr("alt"))
self.assertEqual(self.img.file.url, img.attr("src"))
# now delete the English version
self.img.delete()
self.img = en_img # don't break tearDown
img = pq_img(self.p, "[[Image:test.jpg]]", selector="img", locale="ja")
eq_("test.jpg", img.attr("alt"))
eq_(self.img.file.url, img.attr("src"))
self.assertEqual("test.jpg", img.attr("alt"))
self.assertEqual(self.img.file.url, img.attr("src"))
def test_caption(self):
"""Give the image a caption."""
@ -440,28 +438,28 @@ class TestWikiImageTags(TestCase):
img = img_div("img")
caption = img_div.text()
eq_(self.img.file.url, img.attr("src"))
eq_("my caption", img.attr("alt"))
eq_("my caption", caption)
self.assertEqual(self.img.file.url, img.attr("src"))
self.assertEqual("my caption", img.attr("alt"))
self.assertEqual("my caption", caption)
def test_page_link(self):
"""Link to a wiki page."""
img_a = pq_img(self.p, "[[Image:test.jpg|page=Installing Firefox]]", "a")
img = img_a("img")
eq_("test.jpg", img.attr("alt"))
eq_(self.img.file.url, img.attr("src"))
eq_("/en-US/kb/installing-firefox", img_a.attr("href"))
self.assertEqual("test.jpg", img.attr("alt"))
self.assertEqual(self.img.file.url, img.attr("src"))
self.assertEqual("/en-US/kb/installing-firefox", img_a.attr("href"))
def test_page_link_edit(self):
"""Link to a nonexistent wiki page."""
img_a = pq_img(self.p, "[[Image:test.jpg|page=Article List]]", "a")
img = img_a("img")
eq_("test.jpg", img.attr("alt"))
eq_(self.img.file.url, img.attr("src"))
self.assertEqual("test.jpg", img.attr("alt"))
self.assertEqual(self.img.file.url, img.attr("src"))
assert img_a.hasClass("new")
eq_("/en-US/kb/new?title=Article+List", img_a.attr("href"))
self.assertEqual("/en-US/kb/new?title=Article+List", img_a.attr("href"))
def test_page_link_caption(self):
"""Link to a wiki page with caption and frame."""
@ -470,20 +468,20 @@ class TestWikiImageTags(TestCase):
img = img_a("img")
caption = img_div.text()
eq_("my caption", img.attr("alt"))
eq_("my caption", caption)
eq_(self.img.file.url, img.attr("src"))
self.assertEqual("my caption", img.attr("alt"))
self.assertEqual("my caption", caption)
self.assertEqual(self.img.file.url, img.attr("src"))
assert img_a.hasClass("new")
eq_("/en-US/kb/new?title=A+page", img_a.attr("href"))
self.assertEqual("/en-US/kb/new?title=A+page", img_a.attr("href"))
def test_link(self):
"""Link to an external page."""
img_a = pq_img(self.p, "[[Image:test.jpg|link=http://test.com]]", "a")
img = img_a("img")
eq_("test.jpg", img.attr("alt"))
eq_(self.img.file.url, img.attr("src"))
eq_("http://test.com", img_a.attr("href"))
self.assertEqual("test.jpg", img.attr("alt"))
self.assertEqual(self.img.file.url, img.attr("src"))
self.assertEqual("http://test.com", img_a.attr("href"))
def test_link_caption(self):
"""Link to an external page with caption."""
@ -491,13 +489,13 @@ class TestWikiImageTags(TestCase):
img = img_div("img")
img_a = img_div("a")
eq_(self.img.file.url, img.attr("src"))
eq_("http://ab.us", img_a.attr("href"))
self.assertEqual(self.img.file.url, img.attr("src"))
self.assertEqual("http://ab.us", img_a.attr("href"))
def test_link_align(self):
"""Link with align."""
img_div = pq_img(self.p, "[[Image:test.jpg|link=http://site.com|align=left]]", "div.img")
eq_("img align-left", img_div.attr("class"))
self.assertEqual("img align-left", img_div.attr("class"))
def test_link_align_invalid(self):
"""Link with invalid align."""
@ -507,12 +505,12 @@ class TestWikiImageTags(TestCase):
def test_link_valign(self):
"""Link with valign."""
img = pq_img(self.p, "[[Image:test.jpg|link=http://example.com|valign=top]]")
eq_("vertical-align: top;", img.attr("style"))
self.assertEqual("vertical-align: top;", img.attr("style"))
def test_link_valign_invalid(self):
"""Link with invalid valign."""
img = pq_img(self.p, "[[Image:test.jpg|link=http://example.com|valign=off]]")
eq_(None, img.attr("style"))
self.assertEqual(None, img.attr("style"))
def test_alt(self):
"""Image alt attribute is overriden but caption is not."""
@ -520,14 +518,14 @@ class TestWikiImageTags(TestCase):
img = img_div("img")
caption = img_div.text()
eq_("my alt", img.attr("alt"))
eq_("my caption", caption)
self.assertEqual("my alt", img.attr("alt"))
self.assertEqual("my caption", caption)
def test_alt_empty(self):
"""Image alt attribute can be empty."""
img = pq_img(self.p, "[[Image:test.jpg|alt=|my caption]]")
eq_("", img.attr("alt"))
self.assertEqual("", img.attr("alt"))
def test_alt_unsafe(self):
"""Potentially unsafe alt content is escaped."""
@ -552,37 +550,37 @@ class TestWikiImageTags(TestCase):
"""Image width attribute set."""
img = pq_img(self.p, "[[Image:test.jpg|width=10]]")
eq_("10", img.attr("width"))
self.assertEqual("10", img.attr("width"))
def test_width_invalid(self):
"""Invalid image width attribute set to auto."""
img = pq_img(self.p, "[[Image:test.jpg|width=invalid]]")
eq_(None, img.attr("width"))
self.assertEqual(None, img.attr("width"))
def test_height(self):
"""Image height attribute set."""
img = pq_img(self.p, "[[Image:test.jpg|height=10]]")
eq_("10", img.attr("height"))
self.assertEqual("10", img.attr("height"))
def test_height_invalid(self):
"""Invalid image height attribute set to auto."""
img = pq_img(self.p, "[[Image:test.jpg|height=invalid]]")
eq_(None, img.attr("height"))
self.assertEqual(None, img.attr("height"))
def test_frame(self):
"""Image has frame if specified."""
img_div = pq_img(self.p, "[[Image:test.jpg|frame|caption]]", "div.img")
assert not img_div("img").hasClass("frameless")
eq_("caption", img_div("img").attr("alt"))
eq_("caption", img_div.text())
eq_(self.img.file.url, img_div("img").attr("src"))
self.assertEqual("caption", img_div("img").attr("alt"))
self.assertEqual("caption", img_div.text())
self.assertEqual(self.img.file.url, img_div("img").attr("src"))
def test_frameless_link(self):
"""Image has frameless class and link if specified."""
img_a = pq_img(self.p, "[[Image:test.jpg|page=Installing Firefox]]", "a")
img = img_a("img")
assert "frameless" in img.attr("class")
eq_("/en-US/kb/installing-firefox", img_a.attr("href"))
self.assertEqual("/en-US/kb/installing-firefox", img_a.attr("href"))

Просмотреть файл

@ -4,8 +4,6 @@ from django.conf import settings
from django.db import models
from django.db.utils import DatabaseError
from django.test import TestCase, override_settings
from nose.tools import assert_raises, eq_
from pyquery import PyQuery as pq
from kitsune.questions.models import Question
@ -33,7 +31,8 @@ class ReadOnlyModeTest(TestCase):
@override_settings(READ_ONLY=True)
def test_db_error(self):
assert_raises(DatabaseError, Question.objects.create, id=12)
with self.assertRaises(DatabaseError):
Question.objects.create(id=12)
@override_settings(READ_ONLY=True)
def test_login_error(self):
@ -47,13 +46,13 @@ class ReadOnlyModeTest(TestCase):
},
follow=True,
)
eq_(r.status_code, 503)
self.assertEqual(r.status_code, 503)
title = pq(r.content)("title").text()
assert title.startswith("Maintenance in progress"), title
@override_settings(READ_ONLY=True)
def test_bail_on_post(self):
r = self.client.post("/en-US/questions")
eq_(r.status_code, 503)
self.assertEqual(r.status_code, 503)
title = pq(r.content)("title").text()
assert title.startswith("Maintenance in progress"), title

Просмотреть файл

@ -3,7 +3,6 @@ from django.template.loader import render_to_string
from django.test import override_settings
from django.test.client import RequestFactory
from django.utils import translation
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.sumo.tests import TestCase
@ -15,7 +14,7 @@ from kitsune.sumo.tests import TestCase
#
# doc = pq(response.content)
# href = doc('.breadcrumbs a')[0]
# eq_('/', href.attrib['href'][0])
# self.assertEqual('/', href.attrib['href'][0])
class MockRequestTests(TestCase):
@ -40,14 +39,14 @@ class BaseTemplateTests(MockRequestTests):
def test_dir_ltr(self):
"""Make sure dir attr is set to 'ltr' for LTR language."""
html = render_to_string(self.template, request=self.request)
eq_("ltr", pq(html)("html").attr["dir"])
self.assertEqual("ltr", pq(html)("html").attr["dir"])
def test_dir_rtl(self):
"""Make sure dir attr is set to 'rtl' for RTL language."""
translation.activate("he")
self.request.LANGUAGE_CODE = "he"
html = render_to_string(self.template, request=self.request)
eq_("rtl", pq(html)("html").attr["dir"])
self.assertEqual("rtl", pq(html)("html").attr["dir"])
translation.deactivate()
def test_multi_feeds(self):
@ -60,21 +59,21 @@ class BaseTemplateTests(MockRequestTests):
doc = pq(render_to_string(self.template, {"feeds": feed_urls}, request=self.request))
feeds = doc('link[type="application/atom+xml"]')
eq_(2, len(feeds))
eq_("First Feed", feeds[0].attrib["title"])
eq_("Second Feed", feeds[1].attrib["title"])
self.assertEqual(2, len(feeds))
self.assertEqual("First Feed", feeds[0].attrib["title"])
self.assertEqual("Second Feed", feeds[1].attrib["title"])
def test_readonly_attr(self):
html = render_to_string(self.template, request=self.request)
doc = pq(html)
eq_("false", doc("body")[0].attrib["data-readonly"])
self.assertEqual("false", doc("body")[0].attrib["data-readonly"])
@override_settings(READ_ONLY=True)
def test_readonly_login_link_disabled(self):
"""Ensure that login/register links are hidden in READ_ONLY."""
html = render_to_string(self.template, request=self.request)
doc = pq(html)
eq_(0, len(doc("a.sign-out, a.sign-in")))
self.assertEqual(0, len(doc("a.sign-out, a.sign-in")))
# TODO: Enable this test after the redesign is complete.
# @override_settings(READ_ONLY=False)

Просмотреть файл

@ -2,31 +2,29 @@
from collections import namedtuple
from datetime import datetime
import jinja2
from babel.dates import format_date, format_datetime, format_time
from django.forms.fields import CharField
from django.test.client import RequestFactory
import jinja2
from babel.dates import format_date, format_time, format_datetime
from nose.tools import eq_, assert_raises
from pyquery import PyQuery as pq
from pytz import timezone
from kitsune.sumo.templatetags.jinja_helpers import (
datetimeformat,
DateTimeFormatError,
class_selected,
collapse_linebreaks,
url,
json,
timesince,
label_with_help,
static,
urlparams,
yesno,
number,
remove,
datetimeformat,
f,
fe,
class_selected,
json,
label_with_help,
number,
remove,
static,
timesince,
url,
urlparams,
yesno,
)
from kitsune.sumo.tests import TestCase
from kitsune.sumo.urlresolvers import reverse
@ -35,32 +33,32 @@ from kitsune.sumo.urlresolvers import reverse
class TestHelpers(TestCase):
def test_urlparams_unicode(self):
context = {"q": "Français"}
eq_("/foo?q=Fran%C3%A7ais", urlparams("/foo", **context))
self.assertEqual("/foo?q=Fran%C3%A7ais", urlparams("/foo", **context))
context["q"] = "\u0125help"
eq_("/foo?q=%C4%A5help", urlparams("/foo", **context))
self.assertEqual("/foo?q=%C4%A5help", urlparams("/foo", **context))
def test_urlparams_valid(self):
context = {"a": "foo", "b": "bar"}
eq_("/foo?a=foo&b=bar", urlparams("/foo", **context))
self.assertEqual("/foo?a=foo&b=bar", urlparams("/foo", **context))
def test_urlparams_query_string(self):
eq_("/foo?a=foo&b=bar", urlparams("/foo?a=foo", b="bar"))
self.assertEqual("/foo?a=foo&b=bar", urlparams("/foo?a=foo", b="bar"))
def test_urlparams_multivalue(self):
eq_("/foo?a=foo&a=bar", urlparams("/foo?a=foo&a=bar"))
eq_("/foo?a=bar", urlparams("/foo?a=foo", a="bar"))
self.assertEqual("/foo?a=foo&a=bar", urlparams("/foo?a=foo&a=bar"))
self.assertEqual("/foo?a=bar", urlparams("/foo?a=foo", a="bar"))
def test_urlparams_none(self):
"""Assert a value of None doesn't make it into the query string."""
eq_("/foo", urlparams("/foo", bar=None))
self.assertEqual("/foo", urlparams("/foo", bar=None))
def test_collapse_linebreaks(self):
"""Make sure collapse_linebreaks works on some tricky cases."""
eq_(
self.assertEqual(
collapse_linebreaks("\r\n \t \n\r Trouble\r\n\r\nshooting \r\n"),
"\r\n Trouble\r\nshooting\r\n",
)
eq_(
self.assertEqual(
collapse_linebreaks(
"Application Basics\n \n\n \n "
"\n\n\n \n \n \n "
@ -73,25 +71,25 @@ class TestHelpers(TestCase):
field = CharField(label="Foo", help_text="Foo bar")
field.auto_id = "foo"
expect = '<label for="foo" title="Foo bar">Foo</label>'
eq_(expect, label_with_help(field))
self.assertEqual(expect, label_with_help(field))
def test_yesno(self):
eq_("Yes", yesno(True))
eq_("No", yesno(False))
eq_("Yes", yesno(1))
eq_("No", yesno(0))
self.assertEqual("Yes", yesno(True))
self.assertEqual("No", yesno(False))
self.assertEqual("Yes", yesno(1))
self.assertEqual("No", yesno(0))
def test_number(self):
context = {"request": namedtuple("R", "LANGUAGE_CODE")("en-US")}
eq_("5,000", number(context, 5000))
eq_("", number(context, None))
self.assertEqual("5,000", number(context, 5000))
self.assertEqual("", number(context, None))
def test_remove_in_list(self):
tags = ["tag1", "tag2"]
tag = "tag3"
tags.append(tag)
tags = remove(tags, tag)
eq_(2, len(tags))
self.assertEqual(2, len(tags))
assert tag not in tags
def test_remove_not_in_list(self):
@ -99,7 +97,7 @@ class TestHelpers(TestCase):
tag = "tag3"
tags = remove(tags, tag)
# Nothing was removed and we didn't crash.
eq_(2, len(tags))
self.assertEqual(2, len(tags))
def test_static_failure(self):
"""Should not raise an error if the static file is missing."""
@ -127,7 +125,7 @@ class TestDateTimeFormat(TestCase):
value_localize, format=format, locale=locale, tzinfo=timezone
)
value_returned = datetimeformat(self.context, value_test, format=return_format)
eq_(pq(value_returned)("time").text(), value_expected)
self.assertEqual(pq(value_returned)("time").text(), value_expected)
def test_today(self):
"""Expects shortdatetime, format: Today at {time}."""
@ -137,7 +135,7 @@ class TestDateTimeFormat(TestCase):
value_expected = "Today at %s" % format_time(
date_localize, format="short", locale=self.locale, tzinfo=self.timezone
)
eq_(pq(value_returned)("time").text(), value_expected)
self.assertEqual(pq(value_returned)("time").text(), value_expected)
def test_locale(self):
"""Expects shortdatetime in French."""
@ -157,7 +155,7 @@ class TestDateTimeFormat(TestCase):
value_test = datetime.fromordinal(733900)
value_expected = format_date(value_test, locale=self.locale)
value_returned = datetimeformat(self.context, value_test, format="date")
eq_(pq(value_returned)("time").text(), value_expected)
self.assertEqual(pq(value_returned)("time").text(), value_expected)
def test_time(self):
"""Expects time format."""
@ -165,7 +163,7 @@ class TestDateTimeFormat(TestCase):
value_localize = self.timezone.localize(value_test)
value_expected = format_time(value_localize, locale=self.locale, tzinfo=self.timezone)
value_returned = datetimeformat(self.context, value_test, format="time")
eq_(pq(value_returned)("time").text(), value_expected)
self.assertEqual(pq(value_returned)("time").text(), value_expected)
def test_datetime(self):
"""Expects datetime format."""
@ -178,9 +176,8 @@ class TestDateTimeFormat(TestCase):
def test_unknown_format(self):
"""Unknown format raises DateTimeFormatError."""
date_today = datetime.today()
assert_raises(
DateTimeFormatError, datetimeformat, self.context, date_today, format="unknown"
)
with self.assertRaises(DateTimeFormatError):
datetimeformat(self.context, date_today, format="unknown")
def test_timezone(self):
"""Expects Europe/Paris timezone."""
@ -198,11 +195,12 @@ class TestDateTimeFormat(TestCase):
def test_invalid_value(self):
"""Passing invalid value raises ValueError."""
assert_raises(ValueError, datetimeformat, self.context, "invalid")
with self.assertRaises(ValueError):
datetimeformat(self.context, "invalid")
def test_json_helper(self):
eq_("false", json(False))
eq_('{"foo": "bar"}', json({"foo": "bar"}))
self.assertEqual("false", json(False))
self.assertEqual('{"foo": "bar"}', json({"foo": "bar"}))
class TestUrlHelper(TestCase):
@ -211,7 +209,7 @@ class TestUrlHelper(TestCase):
def test_with_locale(self):
"""Passing a locale to url creates a URL for that locale."""
u = url("home", locale="es")
eq_("/es/", u)
self.assertEqual("/es/", u)
class TimesinceTests(TestCase):
@ -219,16 +217,16 @@ class TimesinceTests(TestCase):
def test_none(self):
"""If None is passed in, timesince returns ''."""
eq_("", timesince(None))
self.assertEqual("", timesince(None))
def test_trunc(self):
"""Assert it returns only the most significant time division."""
eq_("1 year ago", timesince(datetime(2000, 1, 2), now=datetime(2001, 2, 3)))
self.assertEqual("1 year ago", timesince(datetime(2000, 1, 2), now=datetime(2001, 2, 3)))
def test_future(self):
"""Test behavior when date is in the future and also when omitting the
`now` kwarg."""
eq_("", timesince(datetime(9999, 1, 2)))
self.assertEqual("", timesince(datetime(9999, 1, 2)))
class TestFormat(TestCase):
@ -237,12 +235,12 @@ class TestFormat(TestCase):
def test_f_handles_unicode_in_ascii_strings(self):
var = "Pśetergnuś"
# Note that the format string is not a unicode string.
eq_(f("{0}", var), var)
self.assertEqual(f("{0}", var), var)
def test_fe_handles_unicode_in_ascii_strings(self):
var = "Pśetergnuś"
# Note that the format string is not a unicode string.
eq_(fe("{0}", var), var)
self.assertEqual(fe("{0}", var), var)
class TestClassSelected(TestCase):
@ -251,14 +249,14 @@ class TestClassSelected(TestCase):
def test_is_escaped(self):
value_returned = class_selected(1, 1)
type_expected = jinja2.Markup
eq_(type(value_returned), type_expected)
self.assertEqual(type(value_returned), type_expected)
def test_is_selected(self):
value_returned = class_selected(1, 1)
value_expected = 'class="selected"'
eq_(value_returned, value_expected)
self.assertEqual(value_returned, value_expected)
def test_is_not_selected(self):
value_returned = class_selected(0, 1)
value_expected = ""
eq_(value_returned, value_expected)
self.assertEqual(value_returned, value_expected)

Просмотреть файл

@ -2,11 +2,8 @@
from django.core.cache import cache
from nose.tools import eq_
from kitsune.sumo.tests import TestCase
CACHE_KEY = "sumo_cache_flushing_test"
@ -24,4 +21,4 @@ class CacheFlushingTests(TestCase):
def test_2_assert(self):
"""Assert the value stored above isn't there."""
eq_(None, cache.get(CACHE_KEY))
self.assertEqual(None, cache.get(CACHE_KEY))

Просмотреть файл

@ -1,50 +1,48 @@
# -*- coding: utf8 -*-
import json
from unittest.mock import Mock, patch
from django.contrib.auth.models import Permission
from django.test.client import RequestFactory
from django.test.utils import override_settings
from unittest.mock import patch, Mock
from nose.tools import eq_
from parameterized import parameterized
from kitsune.journal.models import Record
from kitsune.sumo.tests import TestCase
from kitsune.sumo.utils import (
chunked,
get_browser,
get_next_url,
has_blocked_link,
is_ratelimited,
smart_int,
truncated_json_dumps,
get_browser,
has_blocked_link,
webpack_static,
)
from kitsune.sumo.tests import TestCase
from kitsune.users.tests import UserFactory
class SmartIntTestCase(TestCase):
def test_sanity(self):
eq_(10, smart_int("10"))
eq_(10, smart_int("10.5"))
self.assertEqual(10, smart_int("10"))
self.assertEqual(10, smart_int("10.5"))
def test_int(self):
eq_(10, smart_int(10))
self.assertEqual(10, smart_int(10))
def test_invalid_string(self):
eq_(0, smart_int("invalid"))
self.assertEqual(0, smart_int("invalid"))
def test_empty_string(self):
eq_(0, smart_int(""))
self.assertEqual(0, smart_int(""))
def test_wrong_type(self):
eq_(0, smart_int(None))
eq_(10, smart_int([], 10))
self.assertEqual(0, smart_int(None))
self.assertEqual(10, smart_int([], 10))
def test_large_values(self):
"""Makes sure ints that would cause an overflow result in fallback."""
eq_(0, smart_int("1" * 1000))
self.assertEqual(0, smart_int("1" * 1000))
class GetNextUrlTests(TestCase):
@ -62,43 +60,43 @@ class GetNextUrlTests(TestCase):
def test_query_string(self):
"""Query-strings remain intact."""
r = self.r.get("/", {"next": "/new?f=b"})
eq_("/new?f=b", get_next_url(r))
self.assertEqual("/new?f=b", get_next_url(r))
def test_good_host_https(self):
"""Full URLs work with valid hosts."""
r = self.r.post("/users/login", {"next": "https://su.mo.com/kb/new"})
eq_("https://su.mo.com/kb/new", get_next_url(r))
self.assertEqual("https://su.mo.com/kb/new", get_next_url(r))
def test_post(self):
"""'next' in POST overrides GET."""
r = self.r.post("/?next=/foo", {"next": "/bar"})
eq_("/bar", get_next_url(r))
self.assertEqual("/bar", get_next_url(r))
def test_get(self):
"""'next' can be a query-string parameter."""
r = self.r.get("/users/login", {"next": "/kb/new"})
eq_("/kb/new", get_next_url(r))
self.assertEqual("/kb/new", get_next_url(r))
def test_referer(self):
"""Use HTTP referer if nothing else."""
r = self.r.get("/")
r.META["HTTP_REFERER"] = "http://su.mo.com/new"
eq_("http://su.mo.com/new", get_next_url(r))
self.assertEqual("http://su.mo.com/new", get_next_url(r))
def test_bad_host_https(self):
r = self.r.get("/", {"next": "https://example.com"})
eq_(None, get_next_url(r))
self.assertEqual(None, get_next_url(r))
def test_bad_host_https_debug(self):
"""If settings.DEBUG == True, bad hosts pass."""
r = self.r.get("/", {"next": "https://example.com"})
with self.settings(DEBUG=True):
eq_("https://example.com", get_next_url(r))
self.assertEqual("https://example.com", get_next_url(r))
def test_bad_host_protocol_relative(self):
"""Protocol-relative URLs do not let bad hosts through."""
r = self.r.get("/", {"next": "//example.com"})
eq_(None, get_next_url(r))
self.assertEqual(None, get_next_url(r))
class JSONTests(TestCase):
@ -106,39 +104,39 @@ class JSONTests(TestCase):
"""Make sure short enough things are unmodified."""
d = {"foo": "bar"}
trunc = truncated_json_dumps(d, 1000, "foo")
eq_(json.dumps(d), trunc)
self.assertEqual(json.dumps(d), trunc)
def test_truncated_key(self):
"""Make sure truncation works as expected."""
d = {"foo": "a long string that should be truncated"}
trunc = truncated_json_dumps(d, 30, "foo")
obj = json.loads(trunc)
eq_(obj["foo"], "a long string that ")
eq_(len(trunc), 30)
self.assertEqual(obj["foo"], "a long string that ")
self.assertEqual(len(trunc), 30)
def test_unicode(self):
"""Unicode should not be treated as longer than it is."""
d = {"formula": "A=πr²"}
trunc = truncated_json_dumps(d, 25, "formula")
eq_(json.dumps(d, ensure_ascii=False), trunc)
self.assertEqual(json.dumps(d, ensure_ascii=False), trunc)
class ChunkedTests(TestCase):
def test_chunked(self):
# chunking nothing yields nothing.
eq_(list(chunked([], 1)), [])
self.assertEqual(list(chunked([], 1)), [])
# chunking list where len(list) < n
eq_(list(chunked([1], 10)), [[1]])
self.assertEqual(list(chunked([1], 10)), [[1]])
# chunking a list where len(list) == n
eq_(list(chunked([1, 2], 2)), [[1, 2]])
self.assertEqual(list(chunked([1, 2], 2)), [[1, 2]])
# chunking list where len(list) > n
eq_(list(chunked([1, 2, 3, 4, 5], 2)), [[1, 2], [3, 4], [5]])
self.assertEqual(list(chunked([1, 2, 3, 4, 5], 2)), [[1, 2], [3, 4], [5]])
# passing in a length overrides the real len(list)
eq_(list(chunked([1, 2, 3, 4, 5, 6, 7], 2, length=4)), [[1, 2], [3, 4]])
self.assertEqual(list(chunked([1, 2, 3, 4, 5, 6, 7], 2, length=4)), [[1, 2], [3, 4]])
class IsRatelimitedTest(TestCase):
@ -150,9 +148,9 @@ class IsRatelimitedTest(TestCase):
request.method = "POST"
# One call to the rate limit won't trigger it.
eq_(is_ratelimited(request, "test-ratelimited", "1/min"), False)
self.assertEqual(is_ratelimited(request, "test-ratelimited", "1/min"), False)
# But two will
eq_(is_ratelimited(request, "test-ratelimited", "1/min"), True)
self.assertEqual(is_ratelimited(request, "test-ratelimited", "1/min"), True)
def test_ratelimit_bypass(self):
u = UserFactory()
@ -164,9 +162,9 @@ class IsRatelimitedTest(TestCase):
request.method = "POST"
# One call to the rate limit won't trigger it.
eq_(is_ratelimited(request, "test-ratelimited", "1/min"), False)
self.assertEqual(is_ratelimited(request, "test-ratelimited", "1/min"), False)
# And a second one still won't, because the user has the bypass permission.
eq_(is_ratelimited(request, "test-ratelimited", "1/min"), False)
self.assertEqual(is_ratelimited(request, "test-ratelimited", "1/min"), False)
def test_ratelimit_logging(self):
u = UserFactory()
@ -175,13 +173,13 @@ class IsRatelimitedTest(TestCase):
request.limited = False
request.method = "POST"
eq_(Record.objects.count(), 0)
self.assertEqual(Record.objects.count(), 0)
# Two calls will trigger the ratelimit once.
is_ratelimited(request, "test-ratelimited", "1/min")
is_ratelimited(request, "test-ratelimited", "1/min")
eq_(Record.objects.count(), 1)
self.assertEqual(Record.objects.count(), 1)
class GetBrowserNameTest(TestCase):
@ -190,7 +188,7 @@ class GetBrowserNameTest(TestCase):
user_agent = "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"
# Check Firefox is returning
eq_(get_browser(user_agent), "Firefox")
self.assertEqual(get_browser(user_agent), "Firefox")
def test_chrome(self):
"""Test with User Agent of Chrome"""
@ -200,20 +198,20 @@ class GetBrowserNameTest(TestCase):
"Chrome/41.0.2228.0 Safari/537.36"
)
# Check Chrome is returning
eq_(get_browser(user_agent), "Chrome")
self.assertEqual(get_browser(user_agent), "Chrome")
def test_internet_explorer(self):
"""Test with User Agent of Internet Explorer"""
# Check with default User Agent of IE 11
user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"
eq_(get_browser(user_agent), "Trident")
self.assertEqual(get_browser(user_agent), "Trident")
# Check with Compatibility View situation user Agent of IE11
user_agent = (
"Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; "
"Trident/7.0; rv:11.0) like Gecko"
)
eq_(get_browser(user_agent), "MSIE")
self.assertEqual(get_browser(user_agent), "MSIE")
def test_safari(self):
"""Test with User Agent of Safari"""
@ -223,7 +221,7 @@ class GetBrowserNameTest(TestCase):
"(KHTML, like Gecko) Version/7.0.3 Safari/7046A194A"
)
# Check Safari is returning
eq_(get_browser(user_agent), "Safari")
self.assertEqual(get_browser(user_agent), "Safari")
class HasLinkTests(TestCase):

Просмотреть файл

@ -1,5 +1,3 @@
from nose.tools import eq_
from kitsune.sumo.tests import TestCase
@ -8,10 +6,10 @@ class TestVanityURLs(TestCase):
def test_windows7(self):
response = self.client.get("/en-US/windows7-support", follow=False)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
assert "home" in response["location"]
def test_contribute(self):
response = self.client.get("/en-US/contribute", follow=False)
eq_(302, response.status_code)
self.assertEqual(302, response.status_code)
assert "get-involved" in response["location"]

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше