Merge pull request #2581 from eviljeff/eq_-be-gone

Finally removing nose from our tests.
This commit is contained in:
Andrew Williamson 2016-05-09 11:41:25 +01:00
Родитель 2ed195dd16 4e84de2f11
Коммит 0ec639f73d
8 изменённых файлов: 445 добавлений и 453 удалений

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

@ -2,8 +2,6 @@
-r prod.txt
execnet==1.2 --hash=sha256:16293a69b17c846371f1ccb9cef10ad88838c9d5239ba26d88b39efb7b432f6f
nose==1.3.4 --hash=sha256:e13d48217efa7a583e151e778fb5489be8b338703bea3d1925afc2599dc359a6 \
--hash=sha256:76bc63a4e2d5e5a0df77ca7d18f0f56e2c46cfb62b71103ba92a92c79fab1e03
psutil==0.2.0 --hash=sha256:a103e3f9d07b7fabcf00d1f1c1c28607ba37e41a7e8e63a61bf62acfa02f506c
py==1.4.30 --hash=sha256:b703e57685ed7c280b1a51c496a4984d83d89def2a930b5e9e5da5a6ca151514 \
--hash=sha256:07e20ab90a550bd3c21891e0d887f0931b4098f148aec95e29b5188f161bb075

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

@ -7,7 +7,6 @@ from django.utils.http import urlsafe_base64_encode
from django.conf import settings
from mock import Mock, patch
from nose.tools import eq_
from pyquery import PyQuery as pq
from olympia import amo
@ -36,7 +35,7 @@ class TestSetPasswordForm(UserFormBase):
def test_url_fail(self):
r = self.client.get('/users/pwreset/junk/', follow=True)
eq_(r.status_code, 404)
assert r.status_code == 404
r = self.client.get('/en-US/firefox/users/pwreset/%s/12-345' %
self.uidb64)
@ -81,9 +80,8 @@ class TestSetPasswordForm(UserFormBase):
self.user_profile = UserProfile.objects.get(id='4043307')
assert self.user_profile.check_password('testlonger')
eq_(self.user_profile.userlog_set
.filter(activity_log__action=amo.LOG.CHANGE_PASSWORD.id)
.count(), 1)
assert self.user_profile.userlog_set.filter(
activity_log__action=amo.LOG.CHANGE_PASSWORD.id).count() == 1
class TestPasswordResetForm(UserFormBase):
@ -94,7 +92,7 @@ class TestPasswordResetForm(UserFormBase):
{'email': 'someemail@somedomain.com'}
)
eq_(len(mail.outbox), 0)
assert len(mail.outbox) == 0
self.assert3xx(r, reverse('password_reset_done'))
def test_request_success(self):
@ -103,7 +101,7 @@ class TestPasswordResetForm(UserFormBase):
{'email': self.user.email}
)
eq_(len(mail.outbox), 1)
assert len(mail.outbox) == 1
assert mail.outbox[0].subject.find('Password reset') == 0
assert mail.outbox[0].body.find('pwreset/%s' % self.uidb64) > 0
@ -131,15 +129,15 @@ class TestPasswordResetForm(UserFormBase):
{'email': self.user.email}
)
eq_(len(mail.outbox), 1)
assert len(mail.outbox) == 1
assert mail.outbox[0].subject.find('Password reset') == 0
assert mail.outbox[0].body.find('pwreset/%s' % self.uidb64) > 0
def test_required_attrs(self):
res = self.client.get(reverse('password_reset_form'))
email_input = pq(res.content.decode('utf-8'))('#id_email')
eq_(email_input.attr('required'), 'required')
eq_(email_input.attr('aria-required'), 'true')
assert email_input.attr('required') == 'required'
assert email_input.attr('aria-required') == 'true'
class TestUserDeleteForm(UserFormBase):
@ -162,10 +160,10 @@ class TestUserDeleteForm(UserFormBase):
data = {'email': 'jbalogh@mozilla.com', 'confirm': True}
self.client.post('/en-US/firefox/users/delete', data, follow=True)
# TODO XXX: Bug 593055
#self.assertContains(r, "Profile Deleted")
# self.assertContains(r, "Profile Deleted")
u = UserProfile.objects.get(id=4043307)
eq_(u.deleted, True)
eq_(u.email, None)
assert u.deleted
assert u.email is None
@patch('olympia.users.models.UserProfile.is_developer')
def test_developer_attempt(self, f):
@ -293,12 +291,12 @@ class TestUserEditForm(UserFormBase):
# Lang is already set: don't change it.
res = self.client.get(self.url)
form = res.context['form']
eq_(form.initial['lang'], 'en-US')
assert form.initial['lang'] == 'en-US'
with self.activate('fr'):
res = self.client.get(reverse('users.edit'))
form = res.context['form']
eq_(form.initial['lang'], 'en-US')
assert form.initial['lang'] == 'en-US'
# Lang isn't set yet: initial value is set to the current locale.
user = UserProfile.objects.get(email='jbalogh@mozilla.com')
@ -307,18 +305,18 @@ class TestUserEditForm(UserFormBase):
res = self.client.get(self.url)
form = res.context['form']
eq_(form.initial['lang'], 'en-US')
assert form.initial['lang'] == 'en-US'
with self.activate('fr'):
res = self.client.get(reverse('users.edit'))
form = res.context['form']
eq_(form.initial['lang'], 'fr')
assert form.initial['lang'] == 'fr'
def test_required_attrs(self):
res = self.client.get(self.url)
email_input = pq(res.content.decode('utf-8'))('#id_email')
eq_(email_input.attr('required'), 'required')
eq_(email_input.attr('aria-required'), 'true')
assert email_input.attr('required') == 'required'
assert email_input.attr('aria-required') == 'true'
def test_existing_email(self):
data = {'email': 'testo@example.com'}
@ -365,8 +363,8 @@ class TestAdminUserEditForm(UserFormBase):
def test_delete_link(self):
r = self.client.get(self.url)
eq_(r.status_code, 200)
eq_(pq(r.content)('a.delete').attr('href'),
assert r.status_code == 200
assert pq(r.content)('a.delete').attr('href') == (
reverse('admin:users_userprofile_delete', args=[self.user.id]))
@ -404,16 +402,16 @@ class TestUserLoginForm(UserFormBase):
url = self._get_login_url()
r = self.client.post(url, {'username': user.email,
'password': 'password'}, follow=True)
eq_(pq(r.content.decode('utf-8'))('.account .user').text(),
assert pq(r.content.decode('utf-8'))('.account .user').text() == (
user.display_name)
eq_(pq(r.content)('.account .user').attr('title'), user.email)
assert pq(r.content)('.account .user').attr('title') == user.email
r = self.client.post(url, {'username': user.email,
'password': 'password',
'rememberme': 1}, follow=True)
eq_(pq(r.content.decode('utf-8'))('.account .user').text(),
assert pq(r.content.decode('utf-8'))('.account .user').text() == (
user.display_name)
eq_(pq(r.content)('.account .user').attr('title'), user.email)
assert pq(r.content)('.account .user').attr('title') == user.email
# Subtract 100 to give some breathing room
age = settings.SESSION_COOKIE_AGE - 100
assert self.client.session.get_expiry_age() > age
@ -462,8 +460,8 @@ class TestUserLoginForm(UserFormBase):
def test_required_attrs(self):
res = self.client.get(self._get_login_url())
username_input = pq(res.content.decode('utf-8'))('#id_username')
eq_(username_input.attr('required'), 'required')
eq_(username_input.attr('aria-required'), 'true')
assert username_input.attr('required') == 'required'
assert username_input.attr('aria-required') == 'true'
def test_disabled_account(self):
url = self._get_login_url()
@ -482,9 +480,9 @@ class TestUserLoginForm(UserFormBase):
self.client.post(url, {'username': 'jbalogh@mozilla.com',
'password': 'password'}, follow=True)
u = UserProfile.objects.get(email='jbalogh@mozilla.com')
eq_(u.failed_login_attempts, 0)
eq_(u.last_login_attempt_ip, '127.0.0.1')
eq_(u.last_login_ip, '127.0.0.1')
assert u.failed_login_attempts == 0
assert u.last_login_attempt_ip == '127.0.0.1'
assert u.last_login_ip == '127.0.0.1'
assert u.last_login_attempt == t or u.last_login_attempt > t
def test_failed_login_logging(self):
@ -495,8 +493,8 @@ class TestUserLoginForm(UserFormBase):
self.client.post(url, {'username': 'jbalogh@mozilla.com',
'password': 'wrongpassword'})
u = UserProfile.objects.get(email='jbalogh@mozilla.com')
eq_(u.failed_login_attempts, 4)
eq_(u.last_login_attempt_ip, '127.0.0.1')
assert u.failed_login_attempts == 4
assert u.last_login_attempt_ip == '127.0.0.1'
assert u.last_login_ip != '127.0.0.1'
assert u.last_login_attempt == t or u.last_login_attempt > t
@ -537,7 +535,7 @@ class TestUserRegisterForm(UserFormBase):
r = self.client.post('/en-US/firefox/users/register', data)
self.assertFormError(r, 'form', 'email',
'User profile with this Email already exists.')
eq_(len(mail.outbox), 0)
assert len(mail.outbox) == 0
def test_set_unmatched_passwords(self):
data = {'email': 'john.connor@sky.net',
@ -546,7 +544,7 @@ class TestUserRegisterForm(UserFormBase):
r = self.client.post('/en-US/firefox/users/register', data)
self.assertFormError(r, 'form', 'password2',
'The passwords did not match.')
eq_(len(mail.outbox), 0)
assert len(mail.outbox) == 0
def test_invalid_username(self):
data = {'email': 'testo@example.com',
@ -668,7 +666,7 @@ class TestUserRegisterForm(UserFormBase):
u = UserProfile.objects.get(email='john.connor@sky.net')
assert u.confirmationcode
eq_(len(mail.outbox), 1)
assert len(mail.outbox) == 1
assert mail.outbox[0].subject.find('Please confirm your email') == 0
assert mail.outbox[0].body.find('%s/confirm/%s' %
(u.id, u.confirmationcode)) > 0

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

@ -4,7 +4,6 @@ import urlparse
import mock
import pytest
from nose.tools import eq_
from pyquery import PyQuery as pq
from olympia import amo
@ -31,50 +30,50 @@ def test_emaillink():
r'<span class="i">null</span>(.*)</span>', obfuscated)
obfuscated = (''.join((m.group(1), m.group(2)))
.replace('&#x0040;', '@').replace('&#x002E;', '.'))[::-1]
eq_(email, obfuscated)
assert email == obfuscated
title = 'E-mail your question'
obfuscated = unicode(emaillink(email, title))
m = re.match(r'<a href="#">(.*)</a>'
r'<span class="emaillink js-hidden">(.*?)'
r'<span class="i">null</span>(.*)</span>', obfuscated)
eq_(title, m.group(1))
assert title == m.group(1)
obfuscated = (''.join((m.group(2), m.group(3)))
.replace('&#x0040;', '@').replace('&#x002E;', '.'))[::-1]
eq_(email, obfuscated)
assert email == obfuscated
def test_user_link():
u = UserProfile(username='jconnor', display_name='John Connor', pk=1)
eq_(user_link(u),
assert user_link(u) == (
'<a href="%s" title="%s">John Connor</a>' % (u.get_url_path(),
u.name))
# handle None gracefully
eq_(user_link(None), '')
assert user_link(None) == ''
def test_user_link_xss():
u = UserProfile(username='jconnor',
display_name='<script>alert(1)</script>', pk=1)
html = "&lt;script&gt;alert(1)&lt;/script&gt;"
eq_(user_link(u), '<a href="%s" title="%s">%s</a>' % (u.get_url_path(),
html, html))
assert user_link(u) == '<a href="%s" title="%s">%s</a>' % (
u.get_url_path(), html, html)
u = UserProfile(username='jconnor',
display_name="""xss"'><iframe onload=alert(3)>""", pk=1)
html = """xss&#34;&#39;&gt;&lt;iframe onload=alert(3)&gt;"""
eq_(user_link(u), '<a href="%s" title="%s">%s</a>' % (u.get_url_path(),
html, html))
assert user_link(u) == '<a href="%s" title="%s">%s</a>' % (
u.get_url_path(), html, html)
def test_users_list():
u1 = UserProfile(username='jconnor', display_name='John Connor', pk=1)
u2 = UserProfile(username='sconnor', display_name='Sarah Connor', pk=2)
eq_(users_list([u1, u2]), ', '.join((user_link(u1), user_link(u2))))
assert users_list([u1, u2]) == ', '.join((user_link(u1), user_link(u2)))
# handle None gracefully
eq_(user_link(None), '')
assert user_link(None) == ''
def test_short_users_list():
@ -84,14 +83,14 @@ def test_short_users_list():
u2 = UserProfile(username='grover', display_name='Grover', pk=2)
u3 = UserProfile(username='cookies!', display_name='Cookie Monster', pk=3)
shortlist = users_list([u1, u2, u3], size=2)
eq_(shortlist, ', '.join((user_link(u1), user_link(u2))) + ', others')
assert shortlist == ', '.join((user_link(u1), user_link(u2))) + ', others'
def test_users_list_truncate_display_name():
u = UserProfile(username='oscar',
display_name='Some Very Long Display Name', pk=1)
truncated_list = users_list([u], None, 10)
eq_(truncated_list,
assert truncated_list == (
u'<a href="%s" title="%s">Some Very...</a>' % (u.get_url_path(),
u.name))
@ -99,12 +98,12 @@ def test_users_list_truncate_display_name():
def test_user_link_unicode():
"""make sure helper won't choke on unicode input"""
u = UserProfile(username=u'jmüller', display_name=u'Jürgen Müller', pk=1)
eq_(user_link(u),
assert user_link(u) == (
u'<a href="%s" title="%s">Jürgen Müller</a>' % (
u.get_url_path(), u.name))
u = UserProfile(username='\xe5\xaf\x92\xe6\x98\x9f', pk=1)
eq_(user_link(u),
assert user_link(u) == (
u'<a href="%s" title="%s">%s</a>' % (u.get_url_path(), u.name,
u.username))
@ -120,12 +119,12 @@ class TestAddonUsersList(TestPersonas, TestCase):
def test_by(self):
"""Test that the by... bit works."""
content = addon_users_list({'amo': amo}, self.addon)
eq_(pq(content).text(), 'by %s' % self.addon.authors.all()[0].name)
assert pq(content).text() == 'by %s' % self.addon.authors.all()[0].name
def test_user_data():
u = user_data(UserProfile(username='foo', pk=1))
eq_(u['anonymous'], False)
assert not u['anonymous']
def test_manage_fxa_link():

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

@ -13,7 +13,6 @@ from django.utils import encoding, translation
import pytest
from mock import patch
from nose.tools import eq_
from olympia import amo
from olympia.amo.tests import TestCase
@ -35,18 +34,18 @@ class TestUserProfile(TestCase):
def test_anonymize(self):
u = UserProfile.objects.get(id='4043307')
eq_(u.email, 'jbalogh@mozilla.com')
assert u.email == 'jbalogh@mozilla.com'
u.anonymize()
x = UserProfile.objects.get(id='4043307')
eq_(x.email, None)
assert x.email is None
def test_email_confirmation_code(self):
u = UserProfile.objects.get(id='4043307')
u.confirmationcode = 'blah'
u.email_confirmation_code()
eq_(len(mail.outbox), 1)
eq_(mail.outbox[0].subject, 'Please confirm your email address')
assert len(mail.outbox) == 1
assert mail.outbox[0].subject == 'Please confirm your email address'
assert mail.outbox[0].body.find('%s/confirm/%s' %
(u.id, u.confirmationcode)) > 0
@ -56,8 +55,8 @@ class TestUserProfile(TestCase):
u.confirmationcode = 'blah'
u.email_confirmation_code()
eq_(len(mail.outbox), 1)
eq_(mail.outbox[0].subject, 'Please confirm your email address')
assert len(mail.outbox) == 1
assert mail.outbox[0].subject == 'Please confirm your email address'
def test_groups_list(self):
user = UserProfile.objects.get(email='jbalogh@mozilla.com')
@ -77,9 +76,9 @@ class TestUserProfile(TestCase):
u1 = UserProfile(username='sc')
u2 = UserProfile(username='sc', display_name="Sarah Connor")
u3 = UserProfile()
eq_(u1.welcome_name, 'sc')
eq_(u2.welcome_name, 'Sarah Connor')
eq_(u3.welcome_name, '')
assert u1.welcome_name == 'sc'
assert u2.welcome_name == 'Sarah Connor'
assert u3.welcome_name == ''
def test_welcome_name_anonymous(self):
user = UserProfile(
@ -187,7 +186,7 @@ class TestUserProfile(TestCase):
review_list = [r.pk for r in u.reviews]
eq_(len(review_list), 1)
assert len(review_list) == 1
assert new_review.pk in review_list, (
'Original review must show up in review list.')
assert new_reply.pk not in review_list, (
@ -198,7 +197,7 @@ class TestUserProfile(TestCase):
AddonUser.objects.create(addon_id=3615, user_id=2519, listed=True)
u = UserProfile.objects.get(id=2519)
addons = u.addons_listed.values_list('id', flat=True)
eq_(sorted(addons), [3615])
assert sorted(addons) == [3615]
def test_addons_not_listed(self):
"""Make sure user is not listed when another is."""
@ -215,7 +214,7 @@ class TestUserProfile(TestCase):
addon2 = Addon.objects.create(name='test-2', type=amo.ADDON_EXTENSION)
AddonUser.objects.create(addon_id=addon2.id, user_id=2519, listed=True)
addons = UserProfile.objects.get(id=2519).my_addons()
eq_(sorted(a.name for a in addons), [addon1.name, addon2.name])
assert sorted(a.name for a in addons) == [addon1.name, addon2.name]
def test_my_addons_with_unlisted_addons(self):
"""Test helper method can return unlisted addons."""
@ -225,42 +224,42 @@ class TestUserProfile(TestCase):
is_listed=False)
AddonUser.objects.create(addon_id=addon2.id, user_id=2519, listed=True)
addons = UserProfile.objects.get(id=2519).my_addons(with_unlisted=True)
eq_(sorted(a.name for a in addons), [addon1.name, addon2.name])
assert sorted(a.name for a in addons) == [addon1.name, addon2.name]
def test_mobile_collection(self):
u = UserProfile.objects.get(id='4043307')
assert not Collection.objects.filter(author=u)
c = u.mobile_collection()
eq_(c.type, amo.COLLECTION_MOBILE)
eq_(c.slug, 'mobile')
assert c.type == amo.COLLECTION_MOBILE
assert c.slug == 'mobile'
def test_favorites_collection(self):
u = UserProfile.objects.get(id='4043307')
assert not Collection.objects.filter(author=u)
c = u.favorites_collection()
eq_(c.type, amo.COLLECTION_FAVORITES)
eq_(c.slug, 'favorites')
assert c.type == amo.COLLECTION_FAVORITES
assert c.slug == 'favorites'
def test_get_url_path(self):
eq_(UserProfile(username='yolo').get_url_path(),
assert UserProfile(username='yolo').get_url_path() == (
'/en-US/firefox/user/yolo/')
eq_(UserProfile(username='yolo', id=1).get_url_path(),
assert UserProfile(username='yolo', id=1).get_url_path() == (
'/en-US/firefox/user/yolo/')
eq_(UserProfile(id=1).get_url_path(),
assert UserProfile(id=1).get_url_path() == (
'/en-US/firefox/user/1/')
eq_(UserProfile(username='<yolo>', id=1).get_url_path(),
assert UserProfile(username='<yolo>', id=1).get_url_path() == (
'/en-US/firefox/user/1/')
@patch.object(settings, 'LANGUAGE_CODE', 'en-US')
def test_activate_locale(self):
eq_(translation.get_language(), 'en-us')
assert translation.get_language() == 'en-us'
with UserProfile(username='yolo').activate_lang():
eq_(translation.get_language(), 'en-us')
assert translation.get_language() == 'en-us'
with UserProfile(username='yolo', lang='fr').activate_lang():
eq_(translation.get_language(), 'fr')
assert translation.get_language() == 'fr'
def test_remove_locale(self):
u = UserProfile.objects.create()
@ -269,7 +268,7 @@ class TestUserProfile(TestCase):
u.remove_locale('fr')
qs = (Translation.objects.filter(localized_string__isnull=False)
.values_list('locale', flat=True))
eq_(sorted(qs.filter(id=u.bio_id)), ['en-US'])
assert sorted(qs.filter(id=u.bio_id)) == ['en-US']
def test_get_fallback(self):
"""Return the translation for the locale fallback."""
@ -351,8 +350,8 @@ class TestPasswords(TestCase):
assert u.check_password(self.utf) is True
# Make sure we updated the old password.
algo, salt, hsh = u.password.split('$')
eq_(algo, 'sha512')
eq_(hsh, get_hexdigest(algo, salt, self.utf))
assert algo == 'sha512'
assert hsh == get_hexdigest(algo, salt, self.utf)
assert u.has_usable_password() is True
def test_valid_new_password(self):
@ -440,17 +439,17 @@ class TestBlacklistedName(TestCase):
fixtures = ['users/test_backends']
def test_blocked(self):
eq_(BlacklistedName.blocked('IE6Fan'), True)
eq_(BlacklistedName.blocked('IE6fantastic'), True)
eq_(BlacklistedName.blocked('IE6'), False)
eq_(BlacklistedName.blocked('testo'), False)
assert BlacklistedName.blocked('IE6Fan')
assert BlacklistedName.blocked('IE6fantastic')
assert not BlacklistedName.blocked('IE6')
assert not BlacklistedName.blocked('testo')
class TestBlacklistedEmailDomain(TestCase):
fixtures = ['users/test_backends']
def test_blocked(self):
eq_(BlacklistedEmailDomain.blocked('mailinator.com'), True)
assert BlacklistedEmailDomain.blocked('mailinator.com')
assert not BlacklistedEmailDomain.blocked('mozilla.com')
@ -478,7 +477,7 @@ class TestUserEmailField(TestCase):
def test_success(self):
user = UserProfile.objects.get(pk=2519)
eq_(UserEmailField().clean(user.email), user)
assert UserEmailField().clean(user.email) == user
def test_failure(self):
with pytest.raises(forms.ValidationError):
@ -504,11 +503,11 @@ class TestUserHistory(TestCase):
def test_user_history(self):
user = UserProfile.objects.create(email='foo@bar.com')
eq_(user.history.count(), 0)
assert user.history.count() == 0
user.update(email='foopy@barby.com')
eq_(user.history.count(), 1)
assert user.history.count() == 1
user.update(email='foopy@barby.com')
eq_(user.history.count(), 1)
assert user.history.count() == 1
def test_user_find(self):
user = UserProfile.objects.create(email='luke@jedi.com')
@ -517,8 +516,8 @@ class TestUserHistory(TestCase):
user.update(email='dark@sith.com')
user.update(email='luke@jedi.com')
user.update(email='dark@sith.com')
eq_([user], list(find_users('luke@jedi.com')))
eq_([user], list(find_users('dark@sith.com')))
assert [user] == list(find_users('luke@jedi.com'))
assert [user] == list(find_users('dark@sith.com'))
def test_user_find_multiple(self):
user_1 = UserProfile.objects.create(username='user_1',
@ -526,7 +525,7 @@ class TestUserHistory(TestCase):
user_1.update(email='dark@sith.com')
user_2 = UserProfile.objects.create(username='user_2',
email='luke@jedi.com')
eq_([user_1, user_2], list(find_users('luke@jedi.com')))
assert [user_1, user_2] == list(find_users('luke@jedi.com'))
class TestUserManager(TestCase):

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

@ -7,7 +7,6 @@ from django.conf import settings
from django.core.files.storage import default_storage as storage
import pytest
from nose.tools import eq_
from PIL import Image
from olympia.amo.tests.test_helpers import get_image_path
@ -42,12 +41,12 @@ def test_resize_photo():
shutil.copyfile(somepic, src.name)
src_image = Image.open(src.name)
eq_(src_image.size, (64, 64))
assert src_image.size == (64, 64)
resize_photo(src.name, dest.name, locally=True)
# Image is smaller than 200x200 so it should stay the same.
dest_image = Image.open(dest.name)
eq_(dest_image.size, (64, 64))
assert dest_image.size == (64, 64)
assert not os.path.exists(src.name)
@ -59,10 +58,10 @@ def test_resize_photo_poorly():
delete=False, dir=settings.TMP_PATH)
shutil.copyfile(somepic, src.name)
src_image = Image.open(src.name)
eq_(src_image.size, (339, 128))
assert src_image.size == (339, 128)
resize_photo(src.name, src.name)
# assert nothing happenned
src_image = Image.open(src.name)
eq_(src_image.size, (339, 128))
assert src_image.size == (339, 128)

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

@ -1,6 +1,5 @@
import fudge
import mock
from nose.tools import eq_
from django.conf import settings
@ -17,8 +16,8 @@ class TestEmailResetCode(TestCase):
token, hash = EmailResetCode.create(id, mail)
r_id, r_mail = EmailResetCode.parse(token, hash)
eq_(id, r_id)
eq_(mail, r_mail)
assert id == r_id
assert mail == r_mail
# A bad token or hash raises ValueError
self.assertRaises(ValueError, EmailResetCode.parse, token, hash[:-5])
@ -28,7 +27,7 @@ class TestEmailResetCode(TestCase):
class TestAutoCreateUsername(TestCase):
def test_invalid_characters(self):
eq_(autocreate_username('testaccount+slug'),
assert autocreate_username('testaccount+slug') == (
'testaccountslug')
def test_empty_username_is_a_random_hash(self):
@ -66,4 +65,4 @@ class TestAutoCreateUsername(TestCase):
.returns(1)
.next_call()
.returns(0))
eq_(autocreate_username('existingname'), 'existingname3')
assert autocreate_username('existingname') == 'existingname3'

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

@ -14,7 +14,6 @@ from django.forms.models import model_to_dict
from django.utils.http import urlsafe_base64_encode
from mock import Mock, patch
from nose.tools import eq_
from olympia import amo
from olympia.amo.tests import TestCase
@ -50,10 +49,10 @@ def fake_request():
def check_sidebar_links(self, expected):
r = self.client.get(self.url)
eq_(r.status_code, 200)
assert r.status_code == 200
links = pq(r.content)('#secondary-nav ul a')
amo.tests.check_links(expected, links)
eq_(links.filter('.selected').attr('href'), self.url)
assert links.filter('.selected').attr('href') == self.url
class TestTShirtOrder(TestCase):
@ -112,14 +111,15 @@ class TestAjax(UserViewBase):
def test_ajax_404(self):
r = self.client.get(reverse('users.ajax'), follow=True)
eq_(r.status_code, 404)
assert r.status_code == 404
def test_ajax_success(self):
r = self.client.get(reverse('users.ajax'), {'q': 'fligtar@gmail.com'},
follow=True)
data = json.loads(r.content)
eq_(data, {'status': 1, 'message': '', 'id': 9945,
'name': u'Justin Scott \u0627\u0644\u062a\u0637\u0628'})
assert data == {
'status': 1, 'message': '', 'id': 9945,
'name': u'Justin Scott \u0627\u0644\u062a\u0637\u0628'}
def test_ajax_xss(self):
self.user.display_name = '<script>alert("xss")</script>'
@ -135,21 +135,21 @@ class TestAjax(UserViewBase):
r = self.client.get(reverse('users.ajax'), {'q': 'incorrect'},
follow=True)
data = json.loads(r.content)
eq_(data,
assert data == (
{'status': 0,
'message': 'A user with that email address does not exist.'})
def test_ajax_failure_no_email(self):
r = self.client.get(reverse('users.ajax'), {'q': ''}, follow=True)
data = json.loads(r.content)
eq_(data,
assert data == (
{'status': 0,
'message': 'An email address is required.'})
def test_forbidden(self):
self.client.logout()
r = self.client.get(reverse('users.ajax'))
eq_(r.status_code, 401)
assert r.status_code == 401
class TestEdit(UserViewBase):
@ -165,10 +165,9 @@ class TestEdit(UserViewBase):
def test_password_logs(self):
res = self.client.post(self.url, self.data)
eq_(res.status_code, 302)
eq_(self.user.userlog_set
.filter(activity_log__action=amo.LOG.CHANGE_PASSWORD.id)
.count(), 1)
assert res.status_code == 302
assert self.user.userlog_set.filter(
activity_log__action=amo.LOG.CHANGE_PASSWORD.id).count() == 1
def test_password_empty(self):
admingroup = Group(rules='Users:Edit')
@ -177,25 +176,25 @@ class TestEdit(UserViewBase):
homepage = {'username': 'jbalogh', 'email': 'jbalogh@mozilla.com',
'homepage': 'http://cbc.ca', 'lang': 'en-US'}
res = self.client.post(self.url, homepage)
eq_(res.status_code, 302)
assert res.status_code == 302
def test_password_blacklisted(self):
BlacklistedPassword.objects.create(password='password')
bad = self.data.copy()
bad['password'] = 'password'
res = self.client.post(self.url, bad)
eq_(res.status_code, 200)
eq_(res.context['form'].is_valid(), False)
eq_(res.context['form'].errors['password'],
assert res.status_code == 200
assert not res.context['form'].is_valid()
assert res.context['form'].errors['password'] == (
[u'That password is not allowed.'])
def test_password_short(self):
bad = self.data.copy()
bad['password'] = 'short'
res = self.client.post(self.url, bad)
eq_(res.status_code, 200)
eq_(res.context['form'].is_valid(), False)
eq_(res.context['form'].errors['password'],
assert res.status_code == 200
assert not res.context['form'].is_valid()
assert res.context['form'].errors['password'] == (
[u'Must be 8 characters or more.'])
def test_email_change_mail_sent(self):
@ -213,8 +212,8 @@ class TestEdit(UserViewBase):
assert u.name == 'DJ SurfNTurf'
assert u.email == 'jbalogh@mozilla.com'
eq_(len(mail.outbox), 1)
eq_(mail.outbox[0].subject.find('Please confirm your email'), 0)
assert len(mail.outbox) == 1
assert mail.outbox[0].subject.find('Please confirm your email') == 0
assert mail.outbox[0].body.find('%s/emailchange/' % self.user.id) > 0
@patch.object(settings, 'SEND_REAL_EMAIL', False)
@ -225,11 +224,11 @@ class TestEdit(UserViewBase):
'lang': 'en-US'}
self.client.post(self.url, data, follow=True)
eq_(len(mail.outbox), 1)
eq_(mail.outbox[0].subject.find('Please confirm your email'), 0)
assert len(mail.outbox) == 1
assert mail.outbox[0].subject.find('Please confirm your email') == 0
def test_edit_bio(self):
eq_(self.get_profile().bio, None)
assert self.get_profile().bio is None
data = {'username': 'jbalogh',
'email': 'jbalogh.changed@mozilla.com',
@ -239,27 +238,28 @@ class TestEdit(UserViewBase):
r = self.client.post(self.url, data, follow=True)
self.assert3xx(r, self.url)
self.assertContains(r, data['bio'])
eq_(unicode(self.get_profile().bio), data['bio'])
assert unicode(self.get_profile().bio) == data['bio']
data['bio'] = 'yyy unst unst'
r = self.client.post(self.url, data, follow=True)
self.assert3xx(r, self.url)
self.assertContains(r, data['bio'])
eq_(unicode(self.get_profile().bio), data['bio'])
assert unicode(self.get_profile().bio) == data['bio']
def check_default_choices(self, choices, checked=True):
doc = pq(self.client.get(self.url).content)
eq_(doc('input[name=notifications]:checkbox').length, len(choices))
assert doc('input[name=notifications]:checkbox').length == len(choices)
for id, label in choices:
box = doc('input[name=notifications][value=%s]' % id)
if checked:
eq_(box.filter(':checked').length, 1)
assert box.filter(':checked').length == 1
else:
eq_(box.length, 1)
assert box.length == 1
parent = box.parent('label')
if checked:
eq_(parent.find('.msg').length, 1) # Check for "NEW" message.
eq_(parent.remove('.msg, .req').text(), label)
# Check for "NEW" message.
assert parent.find('.msg').length == 1
assert parent.remove('.msg, .req').text() == label
def post_notifications(self, choices):
self.check_default_choices(choices)
@ -268,8 +268,8 @@ class TestEdit(UserViewBase):
r = self.client.post(self.url, self.data)
self.assert3xx(r, self.url, 302)
eq_(UserNotification.objects.count(), len(email.NOTIFICATIONS))
eq_(UserNotification.objects.filter(enabled=True).count(),
assert UserNotification.objects.count() == len(email.NOTIFICATIONS)
assert UserNotification.objects.filter(enabled=True).count() == (
len(filter(lambda x: x.mandatory, email.NOTIFICATIONS)))
self.check_default_choices(choices, checked=False)
@ -288,14 +288,14 @@ class TestEdit(UserViewBase):
mandatory = [n.id for n in email.NOTIFICATIONS if n.mandatory]
total = len(self.data['notifications'] + mandatory)
eq_(UserNotification.objects.count(), len(email.NOTIFICATIONS))
eq_(UserNotification.objects.filter(enabled=True).count(), total)
assert UserNotification.objects.count() == len(email.NOTIFICATIONS)
assert UserNotification.objects.filter(enabled=True).count() == total
doc = pq(self.client.get(self.url).content)
eq_(doc('input[name=notifications]:checked').length, total)
assert doc('input[name=notifications]:checked').length == total
eq_(doc('.more-none').length, len(email.NOTIFICATION_GROUPS))
eq_(doc('.more-all').length, len(email.NOTIFICATION_GROUPS))
assert doc('.more-none').length == len(email.NOTIFICATION_GROUPS)
assert doc('.more-all').length == len(email.NOTIFICATION_GROUPS)
def test_edit_notifications_non_dev(self):
self.post_notifications(email.NOTIFICATIONS_CHOICES_NOT_DEV)
@ -307,26 +307,25 @@ class TestEdit(UserViewBase):
def test_collections_toggles(self):
r = self.client.get(self.url)
eq_(r.status_code, 200)
assert r.status_code == 200
doc = pq(r.content)
eq_(doc('#profile-misc').length, 1,
'Collections options should be visible.')
assert doc('#profile-misc').length == 1
def test_remove_locale_bad_request(self):
r = self.client.post(self.user.get_user_url('remove-locale'))
eq_(r.status_code, 400)
assert r.status_code == 400
@patch.object(UserProfile, 'remove_locale')
def test_remove_locale(self, remove_locale_mock):
r = self.client.post(self.user.get_user_url('remove-locale'),
{'locale': 'el'})
eq_(r.status_code, 200)
assert r.status_code == 200
remove_locale_mock.assert_called_with('el')
def test_remove_locale_default_locale(self):
r = self.client.post(self.user.get_user_url('remove-locale'),
{'locale': settings.LANGUAGE_CODE})
eq_(r.status_code, 400)
assert r.status_code == 400
class TestEditAdmin(UserViewBase):
@ -351,46 +350,46 @@ class TestEditAdmin(UserViewBase):
def test_edit(self):
res = self.client.get(self.url)
eq_(res.status_code, 200)
assert res.status_code == 200
def test_edit_without_user_lang(self):
self.regular.lang = None
self.regular.save()
res = self.client.get(self.url)
eq_(res.status_code, 200)
assert res.status_code == 200
def test_edit_forbidden(self):
self.client.logout()
self.client.login(username='editor@mozilla.com', password='password')
res = self.client.get(self.url)
eq_(res.status_code, 403)
assert res.status_code == 403
def test_edit_forbidden_anon(self):
self.client.logout()
res = self.client.get(self.url)
eq_(res.status_code, 302)
assert res.status_code == 302
def test_anonymize(self):
data = self.get_data()
data['anonymize'] = True
res = self.client.post(self.url, data)
eq_(res.status_code, 302)
eq_(self.get_user().password, "sha512$Anonymous$Password")
assert res.status_code == 302
assert self.get_user().password == "sha512$Anonymous$Password"
def test_anonymize_fails(self):
data = self.get_data()
data['anonymize'] = True
data['email'] = 'something@else.com'
res = self.client.post(self.url, data)
eq_(res.status_code, 200)
eq_(self.get_user().password, self.regular.password) # Hasn't changed.
assert res.status_code == 200
assert self.get_user().password == self.regular.password
def test_admin_logs_edit(self):
data = self.get_data()
data['email'] = 'something@else.com'
self.client.post(self.url, data)
res = ActivityLog.objects.filter(action=amo.LOG.ADMIN_USER_EDITED.id)
eq_(res.count(), 1)
assert res.count() == 1
assert self.get_data()['admin_log'] in res[0]._arguments
def test_admin_logs_anonymize(self):
@ -399,7 +398,7 @@ class TestEditAdmin(UserViewBase):
self.client.post(self.url, data)
res = (ActivityLog.objects
.filter(action=amo.LOG.ADMIN_USER_ANONYMIZED.id))
eq_(res.count(), 1)
assert res.count() == 1
assert self.get_data()['admin_log'] in res[0]._arguments
def test_admin_no_password(self):
@ -409,10 +408,10 @@ class TestEditAdmin(UserViewBase):
'oldpassword': 'password'})
self.client.post(self.url, data)
logs = ActivityLog.objects.filter
eq_(logs(action=amo.LOG.CHANGE_PASSWORD.id).count(), 0)
assert logs(action=amo.LOG.CHANGE_PASSWORD.id).count() == 0
res = logs(action=amo.LOG.ADMIN_USER_EDITED.id)
eq_(res.count(), 1)
eq_(res[0].details['password'][0], u'****')
assert res.count() == 1
assert res[0].details['password'][0] == u'****'
def test_delete_user_display_name_xss(self):
# This is to test for bug 835827.
@ -440,15 +439,15 @@ class TestPasswordAdmin(UserViewBase):
def test_password_admin(self):
res = self.client.post(self.url, self.correct, follow=False)
eq_(res.status_code, 200)
eq_(res.context['form'].is_valid(), False)
eq_(res.context['form'].errors['password'],
assert res.status_code == 200
assert not res.context['form'].is_valid()
assert res.context['form'].errors['password'] == (
[u'Letters and numbers required.'])
def test_password(self):
UserProfile.objects.get(username='editor').groups.all().delete()
res = self.client.post(self.url, self.correct, follow=False)
eq_(res.status_code, 302)
assert res.status_code == 302
class TestEmailChange(UserViewBase):
@ -462,25 +461,25 @@ class TestEmailChange(UserViewBase):
# Completely invalid user, valid code
url = reverse('users.emailchange', args=[1234, self.token, self.hash])
r = self.client.get(url, follow=True)
eq_(r.status_code, 404)
assert r.status_code == 404
# User is in the system, but not attached to this code, valid code
url = reverse('users.emailchange', args=[9945, self.token, self.hash])
r = self.client.get(url, follow=True)
eq_(r.status_code, 400)
assert r.status_code == 400
# Valid user, invalid code
url = reverse('users.emailchange', args=[self.user.id, self.token,
self.hash[:-3]])
r = self.client.get(url, follow=True)
eq_(r.status_code, 400)
assert r.status_code == 400
def test_success(self):
assert self.user.email == 'jbalogh@mozilla.com'
url = reverse('users.emailchange', args=[self.user.id, self.token,
self.hash])
r = self.client.get(url, follow=True)
eq_(r.status_code, 200)
assert r.status_code == 200
u = UserProfile.objects.get(id=self.user.id)
assert u.email == 'nobody@mozilla.org'
@ -488,7 +487,7 @@ class TestEmailChange(UserViewBase):
token, hash_ = EmailResetCode.create(self.user.id, 'testo@example.com')
url = reverse('users.emailchange', args=[self.user.id, token, hash_])
r = self.client.get(url, follow=True)
eq_(r.status_code, 400)
assert r.status_code == 400
class TestLogin(UserViewBase):
@ -590,31 +589,31 @@ class TestLogin(UserViewBase):
def test_login_link(self):
r = self.client.get(self.url)
eq_(r.status_code, 200)
eq_(pq(r.content)('#aux-nav li.login').length, 1)
assert r.status_code == 200
assert pq(r.content)('#aux-nav li.login').length == 1
def test_logout_link(self):
self.test_client_login()
r = self.client.get(reverse('home'))
eq_(r.status_code, 200)
eq_(pq(r.content)('#aux-nav li.logout').length, 1)
assert r.status_code == 200
assert pq(r.content)('#aux-nav li.logout').length == 1
@amo.tests.mobile_test
def test_mobile_login(self):
r = self.client.get(self.url)
eq_(r.status_code, 200)
assert r.status_code == 200
doc = pq(r.content)('header')
eq_(doc('nav').length, 1)
eq_(doc('#home').length, 1)
eq_(doc('#auth-nav li.login').length, 0)
assert doc('nav').length == 1
assert doc('#home').length == 1
assert doc('#auth-nav li.login').length == 0
def test_login_ajax(self):
url = reverse('users.login_modal')
r = self.client.get(url)
eq_(r.status_code, 200)
assert r.status_code == 200
res = self.client.post(url, data=self.data)
eq_(res.status_code, 302)
assert res.status_code == 302
def test_login_ajax_error(self):
url = reverse('users.login_modal')
@ -622,7 +621,7 @@ class TestLogin(UserViewBase):
data['username'] = ''
res = self.client.post(url, data=self.data)
eq_(res.context['form'].errors['username'][0],
assert res.context['form'].errors['username'][0] == (
'This field is required.')
def test_login_ajax_wrong(self):
@ -636,13 +635,13 @@ class TestLogin(UserViewBase):
def test_login_no_recaptcha(self):
res = self.client.post(self.url, data=self.data)
eq_(res.status_code, 302)
assert res.status_code == 302
@patch.object(settings, 'NOBOT_RECAPTCHA_PRIVATE_KEY', 'something')
@patch.object(settings, 'LOGIN_RATELIMIT_USER', 2)
def test_login_attempts_recaptcha(self):
res = self.client.post(self.url, data=self.data)
eq_(res.status_code, 200)
assert res.status_code == 200
assert res.context['form'].fields.get('recaptcha')
@patch.object(settings, 'NOBOT_RECAPTCHA_PRIVATE_KEY', 'something')
@ -650,7 +649,7 @@ class TestLogin(UserViewBase):
data = self.data.copy()
data['recaptcha_shown'] = ''
res = self.client.post(self.url, data=data)
eq_(res.status_code, 200)
assert res.status_code == 200
assert res.context['form'].fields.get('recaptcha')
@patch.object(settings, 'NOBOT_RECAPTCHA_PRIVATE_KEY', 'something')
@ -661,14 +660,14 @@ class TestLogin(UserViewBase):
data = self.data.copy()
data.update({'recaptcha': '', 'recaptcha_shown': ''})
res = self.client.post(self.url, data=data)
eq_(res.status_code, 302)
assert res.status_code == 302
def test_login_fails_increment(self):
# It increments even when the form is wrong.
user = UserProfile.objects.filter(email=self.data['username'])
eq_(user.get().failed_login_attempts, 3)
assert user.get().failed_login_attempts == 3
self.client.post(self.url, data={'username': self.data['username']})
eq_(user.get().failed_login_attempts, 4)
assert user.get().failed_login_attempts == 4
def test_doubled_account(self):
"""
@ -688,16 +687,16 @@ class TestLogin(UserViewBase):
res = self.client.post(self.url,
data={'username': 'charlie@example.com',
'password': 'wrongpassword'})
eq_(res.status_code, 200)
eq_(UserProfile.objects.get(email='charlie@example.com')
.failed_login_attempts, 1)
assert res.status_code == 200
assert UserProfile.objects.get(
email='charlie@example.com').failed_login_attempts == 1
res2 = self.client.post(self.url,
data={'username': 'charlie@example.com',
'password': 'bazpassword'})
eq_(res2.status_code, 302)
assert res2.status_code == 302
res3 = self.client.post(self.url, data={'username': 'bob@example.com',
'password': 'foopassword'})
eq_(res3.status_code, 302)
assert res3.status_code == 302
def test_changed_account(self):
"""
@ -712,13 +711,13 @@ class TestLogin(UserViewBase):
res = self.client.post(self.url,
data={'username': 'charlie@example.com',
'password': 'wrongpassword'})
eq_(res.status_code, 200)
eq_(UserProfile.objects.get(email='charlie@example.com')
.failed_login_attempts, 1)
assert res.status_code == 200
assert UserProfile.objects.get(
email='charlie@example.com').failed_login_attempts == 1
res2 = self.client.post(self.url,
data={'username': 'charlie@example.com',
'password': 'bazpassword'})
eq_(res2.status_code, 302)
assert res2.status_code == 302
@patch.object(settings, 'NOBOT_RECAPTCHA_PRIVATE_KEY', '')
@ -736,31 +735,31 @@ class TestFailedCount(UserViewBase):
def test_login_passes(self, log_login_attempt):
self.client.post(self.url, data=self.data)
eq_(self.log_calls(log_login_attempt), [True])
assert self.log_calls(log_login_attempt) == [True]
def test_login_fails(self, log_login_attempt):
self.client.post(self.url, data={'username': self.data['username']})
eq_(self.log_calls(log_login_attempt), [False])
assert self.log_calls(log_login_attempt) == [False]
def test_login_deleted(self, log_login_attempt):
(UserProfile.objects.get(email=self.data['username'])
.update(deleted=True))
self.client.post(self.url, data={'username': self.data['username']})
eq_(self.log_calls(log_login_attempt), [False])
assert self.log_calls(log_login_attempt) == [False]
def test_login_confirmation(self, log_login_attempt):
(UserProfile.objects.get(email=self.data['username'])
.update(confirmationcode='123'))
self.client.post(self.url, data={'username': self.data['username']})
eq_(self.log_calls(log_login_attempt), [False])
assert self.log_calls(log_login_attempt) == [False]
def test_login_get(self, log_login_attempt):
self.client.get(self.url, data={'username': self.data['username']})
eq_(log_login_attempt.called, False)
assert not log_login_attempt.called
def test_login_get_no_data(self, log_login_attempt):
self.client.get(self.url)
eq_(log_login_attempt.called, False)
assert not log_login_attempt.called
class TestUnsubscribe(UserViewBase):
@ -789,13 +788,13 @@ class TestUnsubscribe(UserViewBase):
# Check that it was successful
assert doc('#unsubscribe-success').length
assert doc('#standalone').length
eq_(doc('#standalone ul li').length, 1)
assert doc('#standalone ul li').length == 1
# Make sure the user is unsubscribed
un = UserNotification.objects.filter(notification_id=perm_setting.id,
user=self.user)
eq_(un.count(), 1)
eq_(un.all()[0].enabled, False)
assert un.count() == 1
assert not un.all()[0].enabled
def test_correct_url_new_notification(self):
# Make sure the user is subscribed
@ -814,13 +813,13 @@ class TestUnsubscribe(UserViewBase):
# Check that it was successful
assert doc('#unsubscribe-success').length
assert doc('#standalone').length
eq_(doc('#standalone ul li').length, 1)
assert doc('#standalone ul li').length == 1
# Make sure the user is unsubscribed
un = UserNotification.objects.filter(notification_id=perm_setting.id,
user=self.user)
eq_(un.count(), 1)
eq_(un.all()[0].enabled, False)
assert un.count() == 1
assert not un.all()[0].enabled
def test_wrong_url(self):
perm_setting = email.NOTIFICATIONS[0]
@ -832,7 +831,7 @@ class TestUnsubscribe(UserViewBase):
r = self.client.get(url)
doc = pq(r.content)
eq_(doc('#unsubscribe-fail').length, 1)
assert doc('#unsubscribe-fail').length == 1
class TestReset(UserViewBase):
@ -859,7 +858,7 @@ class TestReset(UserViewBase):
args=self.token),
data={'new_password1': 'spassword',
'new_password2': 'spassword'})
eq_(res.context['form'].errors['new_password1'][0],
assert res.context['form'].errors['new_password1'][0] == (
'Letters and numbers required.')
def test_reset_succeeds(self):
@ -869,7 +868,7 @@ class TestReset(UserViewBase):
data={'new_password1': 'password1',
'new_password2': 'password1'})
assert self.user.reload().check_password('password1')
eq_(res.status_code, 302)
assert res.status_code == 302
def test_reset_incorrect_padding(self):
"""Fixes #929. Even if the b64 padding is incorrect, don't 500."""
@ -938,9 +937,9 @@ class TestLogout(UserViewBase):
user = UserProfile.objects.get(email='jbalogh@mozilla.com')
self.client.login(username=user.email, password='password')
r = self.client.get('/', follow=True)
eq_(pq(r.content.decode('utf-8'))('.account .user').text(),
assert pq(r.content.decode('utf-8'))('.account .user').text() == (
user.display_name)
eq_(pq(r.content)('.account .user').attr('title'), user.email)
assert pq(r.content)('.account .user').attr('title') == user.email
r = self.client.get('/users/logout', follow=True)
assert not pq(r.content)('.account .user')
@ -981,7 +980,7 @@ class TestRegistration(UserViewBase):
url = reverse('users.confirm', args=[self.user.id, 'code'])
r = self.client.get(url, follow=True)
is_anonymous = pq(r.content)('body').attr('data-anonymous')
eq_(json.loads(is_anonymous), True)
assert json.loads(is_anonymous)
self.user.update(confirmationcode='code')
@ -1015,7 +1014,7 @@ class TestRegistration(UserViewBase):
'password': 'foobarbaz',
'password2': 'foobarbaz'})
user = UserProfile.objects.get(email='new@example.com')
eq_(user.lang, 'fr')
assert user.lang == 'fr'
def test_fxa_auth_enabled(self):
"""When FxA is enabled it should render the login page."""
@ -1057,20 +1056,20 @@ class TestProfileLinks(UserViewBase):
# Anonymous user.
links = get_links(self.user.id)
eq_(links.length, 1)
eq_(links.eq(0).attr('href'), reverse('users.abuse',
args=[self.user.id]))
assert links.length == 1
assert links.eq(0).attr('href') == reverse(
'users.abuse', args=[self.user.id])
# Non-admin, someone else's profile.
self.client.login(username='jbalogh@mozilla.com', password='password')
links = get_links(9945)
eq_(links.length, 1)
eq_(links.eq(0).attr('href'), reverse('users.abuse', args=[9945]))
assert links.length == 1
assert links.eq(0).attr('href') == reverse('users.abuse', args=[9945])
# Non-admin, own profile.
links = get_links(self.user.id)
eq_(links.length, 1)
eq_(links.eq(0).attr('href'), reverse('users.edit'))
assert links.length == 1
assert links.eq(0).attr('href') == reverse('users.edit')
# Admin, someone else's profile.
admingroup = Group(rules='Users:Edit')
@ -1080,11 +1079,11 @@ class TestProfileLinks(UserViewBase):
# Admin, own profile.
links = get_links(self.user.id)
eq_(links.length, 2)
eq_(links.eq(0).attr('href'), reverse('users.edit'))
assert links.length == 2
assert links.eq(0).attr('href') == reverse('users.edit')
# TODO XXX Uncomment when we have real user editing pages
#eq_(links.eq(1).attr('href') + "/",
#reverse('admin:users_userprofile_change', args=[self.user.id]))
# assert links.eq(1).attr('href') + "/" == (
# reverse('admin:users_userprofile_change', args=[self.user.id]))
def test_user_properties(self):
self.client.login(username='jbalogh@mozilla.com', password='password')
@ -1106,57 +1105,60 @@ class TestProfileSections(TestCase):
def test_mine_anonymous(self):
res = self.client.get('/user/me/', follow=True)
eq_(res.status_code, 404)
assert res.status_code == 404
def test_mine_authenticated(self):
self.login(self.user)
res = self.client.get('/user/me/', follow=True)
eq_(res.status_code, 200)
eq_(res.context['user'].id, self.user.id)
assert res.status_code == 200
assert res.context['user'].id == self.user.id
def test_my_last_login_anonymous(self):
res = self.client.get(self.url)
eq_(res.status_code, 200)
assert res.status_code == 200
doc = pq(res.content)
eq_(doc('.last-login-time').length, 0)
eq_(doc('.last-login-ip').length, 0)
assert doc('.last-login-time').length == 0
assert doc('.last-login-ip').length == 0
def test_my_last_login_authenticated(self):
self.user.update(last_login_ip='255.255.255.255')
self.login(self.user)
res = self.client.get(self.url)
eq_(res.status_code, 200)
assert res.status_code == 200
doc = pq(res.content)
assert doc('.last-login-time td').text()
eq_(doc('.last-login-ip td').text(), '255.255.255.255')
assert doc('.last-login-ip td').text() == '255.255.255.255'
def test_not_my_last_login(self):
res = self.client.get('/user/999/', follow=True)
eq_(res.status_code, 200)
assert res.status_code == 200
doc = pq(res.content)
eq_(doc('.last-login-time').length, 0)
eq_(doc('.last-login-ip').length, 0)
assert doc('.last-login-time').length == 0
assert doc('.last-login-ip').length == 0
def test_my_addons(self):
eq_(pq(self.client.get(self.url).content)('.num-addons a').length, 0)
assert pq(self.client.get(self.url).content)(
'.num-addons a').length == 0
AddonUser.objects.create(user=self.user, addon_id=3615)
AddonUser.objects.create(user=self.user, addon_id=5299)
r = self.client.get(self.url)
a = r.context['addons'].object_list
eq_(list(a), sorted(a, key=lambda x: x.weekly_downloads, reverse=True))
assert list(a) == sorted(a, key=lambda x: x.weekly_downloads,
reverse=True)
doc = pq(r.content)
eq_(doc('.num-addons a[href="#my-submissions"]').length, 1)
assert doc('.num-addons a[href="#my-submissions"]').length == 1
items = doc('#my-addons .item')
eq_(items.length, 2)
eq_(items('.install[data-addon=3615]').length, 1)
eq_(items('.install[data-addon=5299]').length, 1)
assert items.length == 2
assert items('.install[data-addon=3615]').length == 1
assert items('.install[data-addon=5299]').length == 1
def test_my_unlisted_addons(self):
"""I can't see my own unlisted addons on my profile page."""
eq_(pq(self.client.get(self.url).content)('.num-addons a').length, 0)
assert pq(self.client.get(self.url).content)(
'.num-addons a').length == 0
AddonUser.objects.create(user=self.user, addon_id=3615)
Addon.objects.get(pk=5299).update(is_listed=False)
@ -1168,13 +1170,13 @@ class TestProfileSections(TestCase):
doc = pq(r.content)
items = doc('#my-addons .item')
eq_(items.length, 1)
eq_(items('.install[data-addon=3615]').length, 1)
assert items.length == 1
assert items('.install[data-addon=3615]').length == 1
def test_not_my_unlisted_addons(self):
"""I can't see others' unlisted addons on their profile pages."""
res = self.client.get('/user/999/', follow=True)
eq_(pq(res.content)('.num-addons a').length, 0)
assert pq(res.content)('.num-addons a').length == 0
user = UserProfile.objects.get(pk=999)
AddonUser.objects.create(user=user, addon_id=3615)
@ -1187,11 +1189,12 @@ class TestProfileSections(TestCase):
doc = pq(r.content)
items = doc('#my-addons .item')
eq_(items.length, 1)
eq_(items('.install[data-addon=3615]').length, 1)
assert items.length == 1
assert items('.install[data-addon=3615]').length == 1
def test_my_personas(self):
eq_(pq(self.client.get(self.url).content)('.num-addons a').length, 0)
assert pq(self.client.get(self.url).content)(
'.num-addons a').length == 0
a = amo.tests.addon_factory(type=amo.ADDON_PERSONA)
@ -1201,8 +1204,8 @@ class TestProfileSections(TestCase):
doc = pq(r.content)
items = doc('#my-themes .persona')
eq_(items.length, 1)
eq_(items('a[href="%s"]' % a.get_url_path()).length, 1)
assert items.length == 1
assert items('a[href="%s"]' % a.get_url_path()).length == 1
def test_my_reviews(self):
r = Review.objects.filter(reply_to=None)[0]
@ -1214,8 +1217,8 @@ class TestProfileSections(TestCase):
doc = pq(r.content)('#reviews')
assert not doc.hasClass('full'), (
'reviews should not have "full" class when there are collections')
eq_(doc('.item').length, 1)
eq_(doc('#review-218207').length, 1)
assert doc('.item').length == 1
assert doc('#review-218207').length == 1
# Edit Review form should be present.
self.assertTemplateUsed(r, 'reviews/edit_review.html')
@ -1236,28 +1239,28 @@ class TestProfileSections(TestCase):
# Admins get the Delete Review link.
r = _get_reviews(username='admin@mozilla.com', password='password')
eq_(r.length, 1)
eq_(r.attr('href'), delete_url)
assert r.length == 1
assert r.attr('href') == delete_url
# Editors get the Delete Review link.
r = _get_reviews(username='editor@mozilla.com', password='password')
eq_(r.length, 1)
eq_(r.attr('href'), delete_url)
assert r.length == 1
assert r.attr('href') == delete_url
# Author gets the Delete Review link.
r = _get_reviews(username='regular@mozilla.com', password='password')
eq_(r.length, 1)
eq_(r.attr('href'), delete_url)
assert r.length == 1
assert r.attr('href') == delete_url
# Other user does not get the Delete Review link.
r = _get_reviews(username='clouserw@gmail.com', password='password')
eq_(r.length, 0)
assert r.length == 0
def test_my_reviews_no_pagination(self):
r = self.client.get(self.url)
assert len(self.user.addons_listed) <= 10, (
'This user should have fewer than 10 add-ons.')
eq_(pq(r.content)('#my-addons .paginator').length, 0)
assert pq(r.content)('#my-addons .paginator').length == 0
def test_my_reviews_pagination(self):
for i in xrange(20):
@ -1265,57 +1268,57 @@ class TestProfileSections(TestCase):
assert len(self.user.addons_listed) > 10, (
'This user should have way more than 10 add-ons.')
r = self.client.get(self.url)
eq_(pq(r.content)('#my-addons .paginator').length, 1)
assert pq(r.content)('#my-addons .paginator').length == 1
def test_my_collections_followed(self):
coll = Collection.objects.all()[0]
CollectionWatcher.objects.create(collection=coll, user=self.user)
mine = Collection.objects.listed().filter(following__user=self.user)
eq_(list(mine), [coll])
assert list(mine) == [coll]
r = self.client.get(self.url)
self.assertTemplateUsed(r, 'bandwagon/users/collection_list.html')
eq_(list(r.context['fav_coll']), [coll])
assert list(r.context['fav_coll']) == [coll]
doc = pq(r.content)
eq_(doc('#reviews.full').length, 0)
assert doc('#reviews.full').length == 0
ul = doc('#my-collections #my-favorite')
eq_(ul.length, 1)
assert ul.length == 1
li = ul.find('li')
eq_(li.length, 1)
assert li.length == 1
a = li.find('a')
eq_(a.attr('href'), coll.get_url_path())
eq_(a.text(), unicode(coll.name))
assert a.attr('href') == coll.get_url_path()
assert a.text() == unicode(coll.name)
def test_my_collections_created(self):
coll = Collection.objects.listed().filter(author=self.user)
eq_(len(coll), 1)
assert len(coll) == 1
r = self.client.get(self.url)
self.assertTemplateUsed(r, 'bandwagon/users/collection_list.html')
self.assertSetEqual(r.context['own_coll'], coll)
doc = pq(r.content)
eq_(doc('#reviews.full').length, 0)
assert doc('#reviews.full').length == 0
ul = doc('#my-collections #my-created')
eq_(ul.length, 1)
assert ul.length == 1
li = ul.find('li')
eq_(li.length, 1)
assert li.length == 1
a = li.find('a')
eq_(a.attr('href'), coll[0].get_url_path())
eq_(a.text(), unicode(coll[0].name))
assert a.attr('href') == coll[0].get_url_path()
assert a.text() == unicode(coll[0].name)
def test_no_my_collections(self):
Collection.objects.filter(author=self.user).delete()
r = self.client.get(self.url)
self.assertTemplateNotUsed(r, 'bandwagon/users/collection_list.html')
doc = pq(r.content)
eq_(doc('#my-collections').length, 0)
eq_(doc('#reviews.full').length, 1)
assert doc('#my-collections').length == 0
assert doc('#reviews.full').length == 1
def test_review_abuse_form(self):
r = self.client.get(self.url)
@ -1326,20 +1329,20 @@ class TestProfileSections(TestCase):
r = self.client.get(self.url)
doc = pq(r.content)
button = doc('#profile-actions #report-user-abuse')
eq_(button.length, 1)
eq_(button.attr('href'), abuse_url)
assert button.length == 1
assert button.attr('href') == abuse_url
modal = doc('#popup-staging #report-user-modal.modal')
eq_(modal.length, 1)
eq_(modal('form').attr('action'), abuse_url)
eq_(modal('textarea[name=text]').length, 1)
assert modal.length == 1
assert modal('form').attr('action') == abuse_url
assert modal('textarea[name=text]').length == 1
self.assertTemplateUsed(r, 'users/report_abuse.html')
def test_no_self_abuse(self):
self.client.login(username='clouserw@gmail.com', password='password')
r = self.client.get(self.url)
doc = pq(r.content)
eq_(doc('#profile-actions #report-user-abuse').length, 0)
eq_(doc('#popup-staging #report-user-modal.modal').length, 0)
assert doc('#profile-actions #report-user-abuse').length == 0
assert doc('#popup-staging #report-user-modal.modal').length == 0
self.assertTemplateNotUsed(r, 'users/report_abuse.html')
@ -1352,27 +1355,27 @@ class TestThemesProfile(TestCase):
self.url = self.user.get_user_url('themes')
def _test_good(self, res):
eq_(res.status_code, 200)
assert res.status_code == 200
ids = res.context['addons'].object_list.values_list('id', flat=True)
self.assertSetEqual(ids, [self.theme.id])
doc = pq(res.content)
eq_(doc('.no-results').length, 0)
assert doc('.no-results').length == 0
results = doc('.personas-grid .persona.hovercard')
eq_(results.length, 1)
eq_(results.find('h3').text(), unicode(self.theme.name))
assert results.length == 1
assert results.find('h3').text() == unicode(self.theme.name)
def test_bad_user(self):
res = self.client.get(reverse('users.themes', args=['yolo']))
eq_(res.status_code, 404)
assert res.status_code == 404
def test_no_themes(self):
res = self.client.get(self.url)
eq_(res.status_code, 200)
assert res.status_code == 200
eq_(pq(res.content)('.no-results').length, 1)
assert pq(res.content)('.no-results').length == 1
def test_themes(self):
self.theme = amo.tests.addon_factory(type=amo.ADDON_PERSONA)
@ -1383,7 +1386,7 @@ class TestThemesProfile(TestCase):
def test_bad_category(self):
res = self.client.get(reverse('users.themes', args=['yolo', 'swag']))
eq_(res.status_code, 404)
assert res.status_code == 404
def test_empty_category(self):
self.theme = amo.tests.addon_factory(type=amo.ADDON_PERSONA)
@ -1392,7 +1395,7 @@ class TestThemesProfile(TestCase):
res = self.client.get(
self.user.get_user_url('themes', args=[cat.slug]))
eq_(res.status_code, 200)
assert res.status_code == 200
def test_themes_category(self):
self.theme = amo.tests.addon_factory(type=amo.ADDON_PERSONA)
@ -1417,11 +1420,11 @@ class TestReportAbuse(TestCase):
def test_abuse_anonymous(self, clean):
clean.return_value = ""
self.client.post(self.full_page, {'text': 'spammy'})
eq_(len(mail.outbox), 1)
assert len(mail.outbox) == 1
assert 'spammy' in mail.outbox[0].body
report = AbuseReport.objects.get(user=10482)
eq_(report.message, 'spammy')
eq_(report.reporter, None)
assert report.message == 'spammy'
assert report.reporter is None
def test_abuse_anonymous_fails(self):
r = self.client.post(self.full_page, {'text': 'spammy'})
@ -1430,14 +1433,14 @@ class TestReportAbuse(TestCase):
def test_abuse_logged_in(self):
self.client.login(username='regular@mozilla.com', password='password')
self.client.post(self.full_page, {'text': 'spammy'})
eq_(len(mail.outbox), 1)
assert len(mail.outbox) == 1
assert 'spammy' in mail.outbox[0].body
report = AbuseReport.objects.get(user=10482)
eq_(report.message, 'spammy')
eq_(report.reporter.email, 'regular@mozilla.com')
assert report.message == 'spammy'
assert report.reporter.email == 'regular@mozilla.com'
r = self.client.get(self.full_page)
eq_(pq(r.content)('.notification-box h2').length, 1)
assert pq(r.content)('.notification-box h2').length == 1
class BaseTestMigrateView(TestCase):

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

@ -12,7 +12,6 @@ from django.test.utils import override_settings
import mock
import pytest
from nose.tools import eq_
from pyquery import PyQuery
from olympia import amo
@ -46,29 +45,29 @@ pytestmark = pytest.mark.django_db
def test_version_int():
"""Tests that version_int. Corrects our versions."""
eq_(version_int('3.5.0a1pre2'), 3050000001002)
eq_(version_int(''), 200100)
eq_(version_int('0'), 200100)
eq_(version_int('*'), 99000000200100)
eq_(version_int(MAXVERSION), MAXVERSION)
eq_(version_int(MAXVERSION + 1), MAXVERSION)
eq_(version_int('9999999'), MAXVERSION)
assert version_int('3.5.0a1pre2') == 3050000001002
assert version_int('') == 200100
assert version_int('0') == 200100
assert version_int('*') == 99000000200100
assert version_int(MAXVERSION) == MAXVERSION
assert version_int(MAXVERSION + 1) == MAXVERSION
assert version_int('9999999') == MAXVERSION
def test_version_int_compare():
eq_(version_int('3.6.*'), version_int('3.6.99'))
assert version_int('3.6.*') == version_int('3.6.99')
assert version_int('3.6.*') > version_int('3.6.8')
def test_version_asterix_compare():
eq_(version_int('*'), version_int('99'))
assert version_int('*') == version_int('99')
assert version_int('98.*') < version_int('*')
eq_(version_int('5.*'), version_int('5.99'))
assert version_int('5.*') == version_int('5.99')
assert version_int('5.*') > version_int('5.0.*')
def test_version_dict():
eq_(version_dict('5.0'),
assert version_dict('5.0') == (
{'major': 5,
'minor1': 0,
'minor2': None,
@ -80,19 +79,19 @@ def test_version_dict():
def test_version_int_unicode():
eq_(version_int(u'\u2322 ugh stephend'), 200100)
assert version_int(u'\u2322 ugh stephend') == 200100
def test_dict_from_int():
d = dict_from_int(3050000001002)
eq_(d['major'], 3)
eq_(d['minor1'], 5)
eq_(d['minor2'], 0)
eq_(d['minor3'], 0)
eq_(d['alpha'], 'a')
eq_(d['alpha_ver'], 1)
eq_(d['pre'], 'pre')
eq_(d['pre_ver'], 2)
assert d['major'] == 3
assert d['minor1'] == 5
assert d['minor2'] == 0
assert d['minor3'] == 0
assert d['alpha'] == 'a'
assert d['alpha_ver'] == 1
assert d['pre'] == 'pre'
assert d['pre_ver'] == 2
@pytest.mark.parametrize("addon_type", amo.GROUP_TYPE_ADDON)
@ -140,41 +139,41 @@ class TestVersion(TestCase):
def test_mobile_version_supports_only_mobile_platforms(self):
self.version.apps.all().delete()
self.target_mobile()
eq_(sorted(self.named_plat(self.version.compatible_platforms())),
[u'android'])
assert (sorted(self.named_plat(self.version.compatible_platforms())) ==
[u'android'])
def test_mixed_version_supports_all_platforms(self):
self.target_mobile()
eq_(sorted(self.named_plat(self.version.compatible_platforms())),
['all', 'android', 'linux', 'mac', 'windows'])
assert (sorted(self.named_plat(self.version.compatible_platforms())) ==
['all', 'android', 'linux', 'mac', 'windows'])
def test_non_mobile_version_supports_non_mobile_platforms(self):
eq_(sorted(self.named_plat(self.version.compatible_platforms())),
['all', 'linux', 'mac', 'windows'])
assert (sorted(self.named_plat(self.version.compatible_platforms())) ==
['all', 'linux', 'mac', 'windows'])
def test_major_minor(self):
"""Check that major/minor/alpha is getting set."""
v = Version(version='3.0.12b2')
eq_(v.major, 3)
eq_(v.minor1, 0)
eq_(v.minor2, 12)
eq_(v.minor3, None)
eq_(v.alpha, 'b')
eq_(v.alpha_ver, 2)
assert v.major == 3
assert v.minor1 == 0
assert v.minor2 == 12
assert v.minor3 is None
assert v.alpha == 'b'
assert v.alpha_ver == 2
v = Version(version='3.6.1apre2+')
eq_(v.major, 3)
eq_(v.minor1, 6)
eq_(v.minor2, 1)
eq_(v.alpha, 'a')
eq_(v.pre, 'pre')
eq_(v.pre_ver, 2)
assert v.major == 3
assert v.minor1 == 6
assert v.minor2 == 1
assert v.alpha == 'a'
assert v.pre == 'pre'
assert v.pre_ver == 2
v = Version(version='')
eq_(v.major, None)
eq_(v.minor1, None)
eq_(v.minor2, None)
eq_(v.minor3, None)
assert v.major is None
assert v.minor1 is None
assert v.minor2 is None
assert v.minor3 is None
def test_has_files(self):
v = Version.objects.get(pk=81551)
@ -205,9 +204,9 @@ class TestVersion(TestCase):
def test_version_delete_files(self):
version = Version.objects.get(pk=81551)
eq_(version.files.count(), 1)
assert version.files.count() == 1
version.delete()
eq_(version.files.count(), 1)
assert version.files.count() == 1
def test_version_hard_delete(self):
version = Version.objects.get(pk=81551)
@ -219,18 +218,18 @@ class TestVersion(TestCase):
def test_version_hard_delete_files(self):
version = Version.objects.get(pk=81551)
eq_(version.files.count(), 1)
assert version.files.count() == 1
version.delete(hard=True)
eq_(version.files.count(), 0)
assert version.files.count() == 0
def test_version_delete_logs(self):
user = UserProfile.objects.get(pk=55021)
amo.set_user(user)
# The transform don't know bout my users.
version = Version.objects.get(pk=81551)
eq_(ActivityLog.objects.count(), 0)
assert ActivityLog.objects.count() == 0
version.delete()
eq_(ActivityLog.objects.count(), 2)
assert ActivityLog.objects.count() == 2
def test_version_is_allowed_upload(self):
version = Version.objects.get(pk=81551)
@ -291,15 +290,15 @@ class TestVersion(TestCase):
addon = Addon.objects.get(id=3615)
# The status doesn't change for public files.
qs = File.objects.filter(version=addon.current_version)
eq_(qs.all()[0].status, amo.STATUS_PUBLIC)
assert qs.all()[0].status == amo.STATUS_PUBLIC
Version.objects.create(addon=addon)
eq_(qs.all()[0].status, amo.STATUS_PUBLIC)
assert qs.all()[0].status == amo.STATUS_PUBLIC
assert not hide_mock.called
qs.update(status=amo.STATUS_UNREVIEWED)
version = Version.objects.create(addon=addon)
version.disable_old_files()
eq_(qs.all()[0].status, amo.STATUS_DISABLED)
assert qs.all()[0].status == amo.STATUS_DISABLED
addon.current_version.all_files[0]
assert hide_mock.called
@ -311,12 +310,12 @@ class TestVersion(TestCase):
version = Version.objects.create(addon=addon)
File.objects.create(version=version, status=amo.STATUS_BETA)
version.disable_old_files()
eq_(qs.all()[0].status, amo.STATUS_UNREVIEWED)
assert qs.all()[0].status == amo.STATUS_UNREVIEWED
def test_version_int(self):
version = Version.objects.get(pk=81551)
version.save()
eq_(version.version_int, 2017200200100)
assert version.version_int == 2017200200100
def test_large_version_int(self):
# This version will fail to be written to the version_int
@ -324,26 +323,26 @@ class TestVersion(TestCase):
version = Version.objects.get(pk=81551)
version.version = '1237.2319.32161734.2383290.34'
version.save()
eq_(version.version_int, None)
assert version.version_int is None
def test_version_update_info(self):
addon = Addon.objects.get(pk=3615)
r = self.client.get(reverse('addons.versions.update_info',
args=(addon.slug, self.version.version)))
eq_(r.status_code, 200)
eq_(r['Content-Type'], 'application/xhtml+xml')
eq_(PyQuery(r.content)('p').html(), 'Fix for an important bug')
assert r.status_code == 200
assert r['Content-Type'] == 'application/xhtml+xml'
assert PyQuery(r.content)('p').html() == 'Fix for an important bug'
# Test update info in another language.
with self.activate(locale='fr'):
r = self.client.get(reverse('addons.versions.update_info',
args=(addon.slug,
self.version.version)))
eq_(r.status_code, 200)
eq_(r['Content-Type'], 'application/xhtml+xml')
assert r.status_code == 200
assert r['Content-Type'] == 'application/xhtml+xml'
assert '<br/>' in r.content, (
'Should be using XHTML self-closing tags!')
eq_(PyQuery(r.content)('p').html(),
assert PyQuery(r.content)('p').html() == (
u"Quelque chose en français.<br/><br/>Quelque chose d'autre.")
def test_version_update_info_legacy_redirect(self):
@ -362,17 +361,17 @@ class TestVersion(TestCase):
version = amo.tests.version_factory(addon=addon)
# Base test. Everything is in order, the version should be public.
eq_(version.is_public(), True)
assert version.is_public()
# Non-public file.
self._reset_version(version)
version.all_files[0].status = amo.STATUS_DISABLED
eq_(version.is_public(), False)
assert not version.is_public()
# Deleted version.
self._reset_version(version)
version.deleted = True
eq_(version.is_public(), False)
assert not version.is_public()
# Non-public addon.
self._reset_version(version)
@ -380,22 +379,22 @@ class TestVersion(TestCase):
is_public_path = 'olympia.addons.models.Addon.is_public'
with mock.patch(is_public_path) as is_addon_public:
is_addon_public.return_value = False
eq_(version.is_public(), False)
assert not version.is_public()
def test_is_compatible(self):
# Base test for fixture before the rest.
addon = Addon.objects.get(id=3615)
version = amo.tests.version_factory(addon=addon)
eq_(version.is_compatible[0], True)
eq_(version.is_compatible_app(amo.FIREFOX), True)
assert version.is_compatible[0]
assert version.is_compatible_app(amo.FIREFOX)
def test_is_compatible_type(self):
# Only ADDON_EXTENSIONs should be compatible.
addon = Addon.objects.get(id=3615)
version = amo.tests.version_factory(addon=addon)
addon.update(type=amo.ADDON_PERSONA)
eq_(version.is_compatible[0], False)
eq_(version.is_compatible_app(amo.FIREFOX), True)
assert not version.is_compatible[0]
assert version.is_compatible_app(amo.FIREFOX)
def test_is_compatible_strict_opt_in(self):
# Add-ons opting into strict compatibility should not be compatible.
@ -403,9 +402,9 @@ class TestVersion(TestCase):
version = amo.tests.version_factory(addon=addon)
file = version.all_files[0]
file.update(strict_compatibility=True)
eq_(version.is_compatible[0], False)
assert not version.is_compatible[0]
assert 'strict compatibility' in ''.join(version.is_compatible[1])
eq_(version.is_compatible_app(amo.FIREFOX), True)
assert version.is_compatible_app(amo.FIREFOX)
def test_is_compatible_binary_components(self):
# Add-ons using binary components should not be compatible.
@ -413,19 +412,19 @@ class TestVersion(TestCase):
version = amo.tests.version_factory(addon=addon)
file = version.all_files[0]
file.update(binary_components=True)
eq_(version.is_compatible[0], False)
assert not version.is_compatible[0]
assert 'binary components' in ''.join(version.is_compatible[1])
eq_(version.is_compatible_app(amo.FIREFOX), True)
assert version.is_compatible_app(amo.FIREFOX)
def test_is_compatible_app_max_version(self):
# Add-ons with max app version < 4.0 should not be compatible.
addon = Addon.objects.get(id=3615)
version = amo.tests.version_factory(addon=addon, max_app_version='3.5')
eq_(version.is_compatible_app(amo.FIREFOX), False)
assert not version.is_compatible_app(amo.FIREFOX)
# An app that isn't supported should also be False.
eq_(version.is_compatible_app(amo.THUNDERBIRD), False)
assert not version.is_compatible_app(amo.THUNDERBIRD)
# An app that can't do d2c should also be False.
eq_(version.is_compatible_app(amo.UNKNOWN_APP), False)
assert not version.is_compatible_app(amo.UNKNOWN_APP)
def test_compat_override_app_versions(self):
addon = Addon.objects.get(id=3615)
@ -435,7 +434,7 @@ class TestVersion(TestCase):
max_version=version.version,
min_app_version='10.0a1',
max_app_version='10.*')
eq_(version.compat_override_app_versions(), [('10.0a1', '10.*')])
assert version.compat_override_app_versions() == [('10.0a1', '10.*')]
def test_compat_override_app_versions_wildcard(self):
addon = Addon.objects.get(id=3615)
@ -445,7 +444,7 @@ class TestVersion(TestCase):
max_version='*',
min_app_version='10.0a1',
max_app_version='10.*')
eq_(version.compat_override_app_versions(), [('10.0a1', '10.*')])
assert version.compat_override_app_versions() == [('10.0a1', '10.*')]
@mock.patch('olympia.addons.models.Addon.invalidate_d2c_versions')
def test_invalidate_d2c_version_signals_on_delete(self, inv_mock):
@ -484,12 +483,12 @@ class TestVersion(TestCase):
assert self.version.current_queue == queue
def test_get_url_path(self):
eq_(self.version.get_url_path(),
assert self.version.get_url_path() == (
'/en-US/firefox/addon/a3615/versions/2.1.072')
def test_unlisted_addon_get_url_path(self):
self.version.addon.update(is_listed=False)
eq_(self.version.get_url_path(), '')
assert self.version.get_url_path() == ''
def test_source_upload_path(self):
addon = Addon.objects.get(id=3615)
@ -587,7 +586,7 @@ class TestViews(TestCase):
def test_version_detail_404(self):
r = self.client.get(reverse('addons.versions',
args=[self.addon.slug, 2]))
eq_(r.status_code, 404)
assert r.status_code == 404
def get_content(self, beta=False):
url = reverse('addons.beta-versions' if beta else 'addons.versions',
@ -596,14 +595,14 @@ class TestViews(TestCase):
def test_version_source(self):
self.addon.update(view_source=True)
eq_(len(self.get_content()('a.source-code')), 1)
assert len(self.get_content()('a.source-code')) == 1
def test_version_no_source_one(self):
eq_(len(self.get_content()('a.source-code')), 0)
assert len(self.get_content()('a.source-code')) == 0
def test_version_no_source_two(self):
self.addon.update(view_source=True, status=amo.STATUS_NULL)
eq_(len(self.get_content()('a.source-code')), 0)
assert len(self.get_content()('a.source-code')) == 0
def test_version_link(self):
addon = Addon.objects.get(id=11730)
@ -611,8 +610,8 @@ class TestViews(TestCase):
url = reverse('addons.versions', args=[addon.slug])
doc = PyQuery(self.client.get(url).content)
link = doc('.version h3 > a').attr('href')
eq_(link, reverse('addons.versions', args=[addon.slug, version]))
eq_(doc('.version').attr('id'), 'version-%s' % version)
assert link == reverse('addons.versions', args=[addon.slug, version])
assert doc('.version').attr('id') == 'version-%s' % version
def test_beta_without_beta_builds(self):
doc = self.get_content(beta=True)
@ -653,7 +652,7 @@ class TestFeeds(TestCase):
def test_feed_elements_present(self):
"""specific elements are present and reasonably well formed"""
doc = self.get_feed('a11730')
eq_(doc('rss channel title')[0].text,
assert doc('rss channel title')[0].text == (
'IPv6 Google Search Version History')
assert doc('rss channel link')[0].text.endswith('/en-US/firefox/')
# assert <description> is present
@ -690,7 +689,7 @@ class TestFeeds(TestCase):
relations = dict((link.get('rel'), link.get('href')) for link in rel)
assert relations.pop('first').endswith('format:rss')
eq_(len(relations), len(page_relations))
assert len(relations) == len(page_relations)
for rel, href in relations.iteritems():
page = page_relations[rel]
assert href.endswith('format:rss' if page == 1 else
@ -699,14 +698,14 @@ class TestFeeds(TestCase):
def test_feed_first_page(self):
"""first page has the right elements and page relations"""
doc = self.get_feed('addon-337203', page=1)
eq_(doc('rss item title')[0].text,
assert doc('rss item title')[0].text == (
'Addon for DTC 1.3 - December 5, 2011')
self.assert_page_relations(doc, {'self': 1, 'next': 2, 'last': 4})
def test_feed_middle_page(self):
"""a middle page has the right elements and page relations"""
doc = self.get_feed('addon-337203', page=2)
eq_(doc('rss item title')[0].text,
assert doc('rss item title')[0].text == (
'Addon for DTC 1.2 - December 5, 2011')
self.assert_page_relations(doc, {'previous': 1, 'self': 2, 'next': 3,
'last': 4})
@ -714,20 +713,20 @@ class TestFeeds(TestCase):
def test_feed_last_page(self):
"""last page has the right elements and page relations"""
doc = self.get_feed('addon-337203', page=4)
eq_(doc('rss item title')[0].text,
assert doc('rss item title')[0].text == (
'Addon for DTC 1.0 - December 5, 2011')
self.assert_page_relations(doc, {'previous': 3, 'self': 4, 'last': 4})
def test_feed_invalid_page(self):
"""an invalid page falls back to page 1"""
doc = self.get_feed('addon-337203', page=5)
eq_(doc('rss item title')[0].text,
assert doc('rss item title')[0].text == (
'Addon for DTC 1.3 - December 5, 2011')
def test_feed_no_page(self):
"""no page defaults to page 1"""
doc = self.get_feed('addon-337203')
eq_(doc('rss item title')[0].text,
assert doc('rss item title')[0].text == (
'Addon for DTC 1.3 - December 5, 2011')
@ -748,15 +747,16 @@ class TestDownloadsBase(TestCase):
def assert_served_by_host(self, response, host, file_=None):
if not file_:
file_ = self.file
eq_(response.status_code, 302)
eq_(response.url,
assert response.status_code == 302
assert response.url == (
urlparams('%s%s/%s' % (host, self.addon.id, file_.filename),
filehash=file_.hash))
eq_(response['X-Target-Digest'], file_.hash)
assert response['X-Target-Digest'] == file_.hash
def assert_served_internally(self, response):
eq_(response.status_code, 200)
eq_(response[settings.XSENDFILE_HEADER], self.file.guarded_file_path)
assert response.status_code == 200
assert (response[settings.XSENDFILE_HEADER] ==
self.file.guarded_file_path)
def assert_served_locally(self, response, file_=None, attachment=False):
host = settings.SITE_URL + user_media_url('addons')
@ -820,11 +820,11 @@ class TestDownloads(TestDownloadsBase):
def test_file_404(self):
r = self.client.get(reverse('downloads.file', args=[234]))
eq_(r.status_code, 404)
assert r.status_code == 404
def test_public(self):
eq_(self.addon.status, amo.STATUS_PUBLIC)
eq_(self.file.status, amo.STATUS_PUBLIC)
assert self.addon.status == amo.STATUS_PUBLIC
assert self.file.status == amo.STATUS_PUBLIC
self.assert_served_by_mirror(self.client.get(self.file_url))
def test_public_addon_unreviewed_file(self):
@ -874,21 +874,21 @@ class TestDisabledFileDownloads(TestDownloadsBase):
def test_admin_disabled_404(self):
self.addon.update(status=amo.STATUS_DISABLED)
eq_(self.client.get(self.file_url).status_code, 404)
assert self.client.get(self.file_url).status_code == 404
def test_user_disabled_404(self):
self.addon.update(disabled_by_user=True)
eq_(self.client.get(self.file_url).status_code, 404)
assert self.client.get(self.file_url).status_code == 404
def test_file_disabled_anon_404(self):
self.file.update(status=amo.STATUS_DISABLED)
eq_(self.client.get(self.file_url).status_code, 404)
assert self.client.get(self.file_url).status_code == 404
def test_file_disabled_unprivileged_404(self):
assert self.client.login(username='regular@mozilla.com',
password='password')
self.file.update(status=amo.STATUS_DISABLED)
eq_(self.client.get(self.file_url).status_code, 404)
assert self.client.get(self.file_url).status_code == 404
def test_file_disabled_ok_for_author(self):
self.file.update(status=amo.STATUS_DISABLED)
@ -954,11 +954,11 @@ class TestDownloadsLatest(TestDownloadsBase):
def test_404(self):
url = reverse('downloads.latest', args=[123])
eq_(self.client.get(url).status_code, 404)
assert self.client.get(url).status_code == 404
def test_type_none(self):
r = self.client.get(self.latest_url)
eq_(r.status_code, 302)
assert r.status_code == 302
url = self.file_url + '/' + self.file.filename
assert r['Location'].endswith(url), r['Location']
@ -996,7 +996,7 @@ class TestDownloadsLatest(TestDownloadsBase):
# But we can't match platform=3.
url = reverse('downloads.latest',
kwargs={'addon_id': self.addon.slug, 'platform': 3})
eq_(self.client.get(url).status_code, 404)
assert self.client.get(url).status_code == 404
def test_type(self):
url = reverse('downloads.latest', kwargs={'addon_id': self.addon.slug,
@ -1026,7 +1026,7 @@ class TestDownloadsLatest(TestDownloadsBase):
def test_query_params(self):
url = self.latest_url + '?src=xxx'
r = self.client.get(url)
eq_(r.status_code, 302)
assert r.status_code == 302
assert r['Location'].endswith('?src=xxx'), r['Location']
@ -1057,7 +1057,7 @@ class TestDownloadSource(TestCase):
def test_owner_should_be_allowed(self):
self.client.login(username=self.user.email, password="password")
response = self.client.get(self.url)
eq_(response.status_code, 200)
assert response.status_code == 200
assert response[settings.XSENDFILE_HEADER]
assert 'Content-Disposition' in response
filename = self.filename
@ -1071,13 +1071,13 @@ class TestDownloadSource(TestCase):
def test_anonymous_should_not_be_allowed(self):
response = self.client.get(self.url)
eq_(response.status_code, 404)
assert response.status_code == 404
def test_group_binarysource_should_be_allowed(self):
GroupUser.objects.create(user=self.user, group=self.group)
self.client.login(username=self.user.email, password="password")
response = self.client.get(self.url)
eq_(response.status_code, 200)
assert response.status_code == 200
assert response[settings.XSENDFILE_HEADER]
assert 'Content-Disposition' in response
filename = self.filename
@ -1093,7 +1093,7 @@ class TestDownloadSource(TestCase):
self.version.source = None
self.version.save()
response = self.client.get(self.url)
eq_(response.status_code, 404)
assert response.status_code == 404
@mock.patch.object(acl, 'check_addons_reviewer', lambda x: False)
@mock.patch.object(acl, 'check_unlisted_addons_reviewer', lambda x: False)
@ -1151,51 +1151,51 @@ class TestExtensionVersionFromUpload(TestVersionFromUpload):
def test_carry_over_old_license(self):
version = Version.from_upload(self.upload, self.addon,
[self.platform])
eq_(version.license_id, self.addon.current_version.license_id)
assert version.license_id == self.addon.current_version.license_id
def test_carry_over_license_no_version(self):
self.addon.versions.all().delete()
version = Version.from_upload(self.upload, self.addon,
[self.platform])
eq_(version.license_id, None)
assert version.license_id is None
def test_app_versions(self):
version = Version.from_upload(self.upload, self.addon,
[self.platform])
assert amo.FIREFOX in version.compatible_apps
app = version.compatible_apps[amo.FIREFOX]
eq_(app.min.version, '3.0')
eq_(app.max.version, '3.6.*')
assert app.min.version == '3.0'
assert app.max.version == '3.6.*'
def test_version_number(self):
version = Version.from_upload(self.upload, self.addon,
[self.platform])
eq_(version.version, '0.1')
assert version.version == '0.1'
def test_file_platform(self):
version = Version.from_upload(self.upload, self.addon,
[self.platform])
files = version.all_files
eq_(len(files), 1)
eq_(files[0].platform, self.platform)
assert len(files) == 1
assert files[0].platform == self.platform
def test_file_name(self):
version = Version.from_upload(self.upload, self.addon,
[self.platform])
files = version.all_files
eq_(files[0].filename, u'delicious_bookmarks-0.1-fx-mac.xpi')
assert files[0].filename == u'delicious_bookmarks-0.1-fx-mac.xpi'
def test_file_name_platform_all(self):
version = Version.from_upload(self.upload, self.addon,
[amo.PLATFORM_ALL.id])
files = version.all_files
eq_(files[0].filename, u'delicious_bookmarks-0.1-fx.xpi')
assert files[0].filename == u'delicious_bookmarks-0.1-fx.xpi'
def test_android_creates_platform_files(self):
version = Version.from_upload(self.upload, self.addon,
[amo.PLATFORM_ANDROID.id])
files = version.all_files
eq_(sorted(amo.PLATFORMS[f.platform].shortname for f in files),
assert sorted(amo.PLATFORMS[f.platform].shortname for f in files) == (
['android'])
def test_desktop_all_android_creates_all(self):
@ -1205,7 +1205,7 @@ class TestExtensionVersionFromUpload(TestVersionFromUpload):
[amo.PLATFORM_ALL.id, amo.PLATFORM_ANDROID.id]
)
files = version.all_files
eq_(sorted(amo.PLATFORMS[f.platform].shortname for f in files),
assert sorted(amo.PLATFORMS[f.platform].shortname for f in files) == (
['all', 'android'])
def test_android_with_mixed_desktop_creates_platform_files(self):
@ -1215,7 +1215,7 @@ class TestExtensionVersionFromUpload(TestVersionFromUpload):
[amo.PLATFORM_LINUX.id, amo.PLATFORM_ANDROID.id]
)
files = version.all_files
eq_(sorted(amo.PLATFORMS[f.platform].shortname for f in files),
assert sorted(amo.PLATFORMS[f.platform].shortname for f in files) == (
['android', 'linux'])
def test_multiple_platforms(self):
@ -1227,20 +1227,17 @@ class TestExtensionVersionFromUpload(TestVersionFromUpload):
assert not storage.exists(self.upload.path), (
"Expected original upload to move but it still exists.")
files = version.all_files
eq_(len(files), 2)
eq_(sorted([f.platform for f in files]),
assert len(files) == 2
assert sorted([f.platform for f in files]) == (
sorted(platforms))
eq_(sorted([f.filename for f in files]),
assert sorted([f.filename for f in files]) == (
[u'delicious_bookmarks-0.1-fx-%s.xpi' % (
amo.PLATFORM_LINUX.shortname),
u'delicious_bookmarks-0.1-fx-%s.xpi' % (
amo.PLATFORM_MAC.shortname)])
for file_ in files:
with storage.open(file_.file_path) as f:
eq_(uploaded_hash,
hashlib.md5(f.read()).hexdigest(),
"md5 hash of %r does not match uploaded file" % (
file_.file_path))
assert uploaded_hash == hashlib.md5(f.read()).hexdigest()
def test_file_multi_package(self):
version = Version.from_upload(self.get_upload('multi-package.xpi'),
@ -1285,21 +1282,21 @@ class TestSearchVersionFromUpload(TestVersionFromUpload):
def test_version_number(self):
version = Version.from_upload(self.upload, self.addon,
[self.platform])
eq_(version.version, self.now)
assert version.version == self.now
def test_file_name(self):
version = Version.from_upload(self.upload, self.addon,
[self.platform])
files = version.all_files
eq_(files[0].filename,
assert files[0].filename == (
u'delicious_bookmarks-%s.xml' % self.now)
def test_file_platform_is_always_all(self):
version = Version.from_upload(self.upload, self.addon,
[self.platform])
files = version.all_files
eq_(len(files), 1)
eq_(files[0].platform, amo.PLATFORM_ALL.id)
assert len(files) == 1
assert files[0].platform == amo.PLATFORM_ALL.id
class TestStatusFromUpload(TestVersionFromUpload):
@ -1312,13 +1309,13 @@ class TestStatusFromUpload(TestVersionFromUpload):
def test_status(self):
self.current.files.all().update(status=amo.STATUS_UNREVIEWED)
Version.from_upload(self.upload, self.addon, [self.platform])
eq_(File.objects.filter(version=self.current)[0].status,
assert File.objects.filter(version=self.current)[0].status == (
amo.STATUS_DISABLED)
def test_status_beta(self):
# Check that the add-on + files are in the public status.
eq_(self.addon.status, amo.STATUS_PUBLIC)
eq_(File.objects.filter(version=self.current)[0].status,
assert self.addon.status == amo.STATUS_PUBLIC
assert File.objects.filter(version=self.current)[0].status == (
amo.STATUS_PUBLIC)
# Create a new under review version with a pending file.
upload = self.get_upload('extension-0.2.xpi')
@ -1329,14 +1326,14 @@ class TestStatusFromUpload(TestVersionFromUpload):
beta_version = Version.from_upload(upload, self.addon, [self.platform],
is_beta=True)
# Check that it doesn't modify the public status.
eq_(self.addon.status, amo.STATUS_PUBLIC)
eq_(File.objects.filter(version=self.current)[0].status,
assert self.addon.status == amo.STATUS_PUBLIC
assert File.objects.filter(version=self.current)[0].status == (
amo.STATUS_PUBLIC)
# Check that the file created with the beta version is in beta status.
eq_(File.objects.filter(version=beta_version)[0].status,
assert File.objects.filter(version=beta_version)[0].status == (
amo.STATUS_BETA)
# Check that the previously uploaded version is still pending.
eq_(File.objects.filter(version=new_version)[0].status,
assert File.objects.filter(version=new_version)[0].status == (
amo.STATUS_PENDING)
@ -1344,7 +1341,7 @@ class TestMobileVersions(TestMobile):
def test_versions(self):
r = self.client.get(reverse('addons.versions', args=['a3615']))
eq_(r.status_code, 200)
assert r.status_code == 200
self.assertTemplateUsed(r, 'versions/mobile/version_list.html')
@ -1357,34 +1354,34 @@ class TestApplicationsVersions(TestCase):
def test_repr_when_compatible(self):
addon = addon_factory(version_kw=self.version_kw)
version = addon.current_version
eq_(version.apps.all()[0].__unicode__(), 'Firefox 5.0 and later')
assert version.apps.all()[0].__unicode__() == 'Firefox 5.0 and later'
def test_repr_when_strict(self):
addon = addon_factory(version_kw=self.version_kw,
file_kw=dict(strict_compatibility=True))
version = addon.current_version
eq_(version.apps.all()[0].__unicode__(), 'Firefox 5.0 - 6.*')
assert version.apps.all()[0].__unicode__() == 'Firefox 5.0 - 6.*'
def test_repr_when_binary(self):
addon = addon_factory(version_kw=self.version_kw,
file_kw=dict(binary_components=True))
version = addon.current_version
eq_(version.apps.all()[0].__unicode__(), 'Firefox 5.0 - 6.*')
assert version.apps.all()[0].__unicode__() == 'Firefox 5.0 - 6.*'
def test_repr_when_not_extension(self):
addon = addon_factory(type=amo.ADDON_THEME,
version_kw=self.version_kw)
version = addon.current_version
eq_(version.apps.all()[0].__unicode__(), 'Firefox 5.0 - 6.*')
assert version.apps.all()[0].__unicode__() == 'Firefox 5.0 - 6.*'
def test_repr_when_low_app_support(self):
addon = addon_factory(version_kw=dict(min_app_version='3.0',
max_app_version='3.5'))
version = addon.current_version
eq_(version.apps.all()[0].__unicode__(), 'Firefox 3.0 - 3.5')
assert version.apps.all()[0].__unicode__() == 'Firefox 3.0 - 3.5'
def test_repr_when_unicode(self):
addon = addon_factory(version_kw=dict(min_app_version=u'ك',
max_app_version=u'ك'))
version = addon.current_version
eq_(unicode(version.apps.all()[0]), u'Firefox ك - ك')
assert unicode(version.apps.all()[0]) == u'Firefox ك - ك'