Lots of code cleanup, no functionality change

This commit is contained in:
Oliver Falk
2025-02-10 13:27:48 +01:00
parent 04a39f7693
commit 4a892b0c4c
7 changed files with 139 additions and 148 deletions

View File

@@ -1,5 +1,5 @@
[flake8] [flake8]
ignore = E501, W503, E402, C901 ignore = E501, W503, E402, C901, E231
max-line-length = 79 max-line-length = 79
max-complexity = 18 max-complexity = 18
select = B,C,E,F,W,T4,B9 select = B,C,E,F,W,T4,B9

View File

@@ -3,7 +3,7 @@
Default: useful variables for the base page templates. Default: useful variables for the base page templates.
""" """
from ipware import get_client_ip from ipware import get_client_ip # type: ignore
from ivatar.settings import IVATAR_VERSION, SITE_NAME, MAX_PHOTO_SIZE from ivatar.settings import IVATAR_VERSION, SITE_NAME, MAX_PHOTO_SIZE
from ivatar.settings import BASE_URL, SECURE_BASE_URL from ivatar.settings import BASE_URL, SECURE_BASE_URL
from ivatar.settings import MAX_NUM_UNCONFIRMED_EMAILS from ivatar.settings import MAX_NUM_UNCONFIRMED_EMAILS
@@ -28,6 +28,7 @@ def basepage(request):
context["BASE_URL"] = BASE_URL context["BASE_URL"] = BASE_URL
context["SECURE_BASE_URL"] = SECURE_BASE_URL context["SECURE_BASE_URL"] = SECURE_BASE_URL
context["max_emails"] = False context["max_emails"] = False
if request.user: if request.user:
if not request.user.is_anonymous: if not request.user.is_anonymous:
unconfirmed = request.user.unconfirmedemail_set.count() unconfirmed = request.user.unconfirmedemail_set.count()

View File

@@ -22,29 +22,23 @@ def get_photo(email):
+ "?s=%i&d=404" % AVATAR_MAX_SIZE + "?s=%i&d=404" % AVATAR_MAX_SIZE
) )
image_url = ( image_url = (
"https://secure.gravatar.com/avatar/" + hash_object.hexdigest() + "?s=512&d=404" f"https://secure.gravatar.com/avatar/{hash_object.hexdigest()}?s=512&d=404"
) )
# Will redirect to the public profile URL if it exists # Will redirect to the public profile URL if it exists
service_url = "http://www.gravatar.com/" + hash_object.hexdigest() service_url = f"http://www.gravatar.com/{hash_object.hexdigest()}"
try: try:
urlopen(image_url) urlopen(image_url)
except HTTPError as exc: except HTTPError as exc:
if exc.code != 404 and exc.code != 503: if exc.code not in [404, 503]:
print( # pragma: no cover print(f"Gravatar fetch failed with an unexpected {exc.code} HTTP error")
"Gravatar fetch failed with an unexpected %s HTTP error" % exc.code
)
return False return False
except URLError as exc: # pragma: no cover except URLError as exc: # pragma: no cover
print( print(f"Gravatar fetch failed with URL error: {exc.reason}")
"Gravatar fetch failed with URL error: %s" % exc.reason
) # pragma: no cover
return False # pragma: no cover return False # pragma: no cover
except SSLError as exc: # pragma: no cover except SSLError as exc: # pragma: no cover
print( print(f"Gravatar fetch failed with SSL error: {exc.reason}")
"Gravatar fetch failed with SSL error: %s" % exc.reason
) # pragma: no cover
return False # pragma: no cover return False # pragma: no cover
return { return {

View File

@@ -142,8 +142,7 @@ class Photo(BaseAccountModel):
image_url = False image_url = False
if service_name == "Gravatar": if service_name == "Gravatar":
gravatar = get_gravatar_photo(email_address) if gravatar := get_gravatar_photo(email_address):
if gravatar:
image_url = gravatar["image_url"] image_url = gravatar["image_url"]
if service_name == "Libravatar": if service_name == "Libravatar":
@@ -153,15 +152,11 @@ class Photo(BaseAccountModel):
return False # pragma: no cover return False # pragma: no cover
try: try:
image = urlopen(image_url) image = urlopen(image_url)
# No idea how to test this
# pragma: no cover
except HTTPError as exc: except HTTPError as exc:
print("%s import failed with an HTTP error: %s" % (service_name, exc.code)) print(f"{service_name} import failed with an HTTP error: {exc.code}")
return False return False
# No idea how to test this
# pragma: no cover
except URLError as exc: except URLError as exc:
print("%s import failed: %s" % (service_name, exc.reason)) print(f"{service_name} import failed: {exc.reason}")
return False return False
data = image.read() data = image.read()
@@ -173,7 +168,7 @@ class Photo(BaseAccountModel):
self.format = file_format(img.format) self.format = file_format(img.format)
if not self.format: if not self.format:
print("Unable to determine format: %s" % img) # pragma: no cover print(f"Unable to determine format: {img}")
return False # pragma: no cover return False # pragma: no cover
self.data = data self.data = data
super().save() super().save()
@@ -188,10 +183,9 @@ class Photo(BaseAccountModel):
# Use PIL to read the file format # Use PIL to read the file format
try: try:
img = Image.open(BytesIO(self.data)) img = Image.open(BytesIO(self.data))
# Testing? Ideas anyone?
except Exception as exc: # pylint: disable=broad-except except Exception as exc: # pylint: disable=broad-except
# For debugging only # For debugging only
print("Exception caught in Photo.save(): %s" % exc) print(f"Exception caught in Photo.save(): {exc}")
return False return False
self.format = file_format(img.format) self.format = file_format(img.format)
if not self.format: if not self.format:
@@ -301,8 +295,7 @@ class ConfirmedEmailManager(models.Manager):
external_photos = [] external_photos = []
if is_logged_in: if is_logged_in:
gravatar = get_gravatar_photo(confirmed.email) if gravatar := get_gravatar_photo(confirmed.email):
if gravatar:
external_photos.append(gravatar) external_photos.append(gravatar)
return (confirmed.pk, external_photos) return (confirmed.pk, external_photos)
@@ -354,7 +347,6 @@ class ConfirmedEmail(BaseAccountModel):
avatar = bs.get_profile(handle) avatar = bs.get_profile(handle)
if not avatar: if not avatar:
raise Exception("Invalid Bluesky handle") raise Exception("Invalid Bluesky handle")
return
self.bluesky_handle = handle self.bluesky_handle = handle
self.save() self.save()
@@ -430,7 +422,7 @@ class UnconfirmedEmail(BaseAccountModel):
try: try:
send_mail(email_subject, email_body, DEFAULT_FROM_EMAIL, [self.email]) send_mail(email_subject, email_body, DEFAULT_FROM_EMAIL, [self.email])
except Exception as e: except Exception as e:
self.last_status = "%s" % e self.last_status = f"{e}"
self.save() self.save()
return True return True
@@ -508,7 +500,6 @@ class ConfirmedOpenId(BaseAccountModel):
avatar = bs.get_profile(handle) avatar = bs.get_profile(handle)
if not avatar: if not avatar:
raise Exception("Invalid Bluesky handle") raise Exception("Invalid Bluesky handle")
return
self.bluesky_handle = handle self.bluesky_handle = handle
self.save() self.save()
@@ -518,7 +509,7 @@ class ConfirmedOpenId(BaseAccountModel):
url = urlsplit(self.openid) url = urlsplit(self.openid)
if url.username: # pragma: no cover if url.username: # pragma: no cover
password = url.password or "" password = url.password or ""
netloc = url.username + ":" + password + "@" + url.hostname netloc = f"{url.username}:{password}@{url.hostname}"
else: else:
netloc = url.hostname netloc = url.hostname
lowercase_url = urlunsplit( lowercase_url = urlunsplit(
@@ -638,9 +629,7 @@ class DjangoOpenIDStore(OpenIDStore):
self.removeAssociation(server_url, assoc.handle) self.removeAssociation(server_url, assoc.handle)
else: else:
associations.append((association.issued, association)) associations.append((association.issued, association))
if not associations: return associations[-1][1] if associations else None
return None
return associations[-1][1]
@staticmethod @staticmethod
def removeAssociation(server_url, handle): # pragma: no cover def removeAssociation(server_url, handle): # pragma: no cover
@@ -693,6 +682,6 @@ class DjangoOpenIDStore(OpenIDStore):
""" """
Helper method to cleanup associations Helper method to cleanup associations
""" """
OpenIDAssociation.objects.extra( # pylint: disable=no-member OpenIDAssociation.objects.extra(
where=["issued + lifetimeint < (%s)" % time.time()] where=[f"issued + lifetimeint < ({time.time()})"]
).delete() ).delete()

View File

@@ -2,6 +2,9 @@
""" """
Test our views in ivatar.ivataraccount.views and ivatar.views Test our views in ivatar.ivataraccount.views and ivatar.views
""" """
import contextlib
# pylint: disable=too-many-lines # pylint: disable=too-many-lines
from urllib.parse import urlsplit from urllib.parse import urlsplit
from io import BytesIO from io import BytesIO
@@ -240,9 +243,11 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
"Confirm w/o verification key does not produce error message?", "Confirm w/o verification key does not produce error message?",
) )
def test_confirm_email_w_inexisting_auth_key(self): # pylint: disable=invalid-name def test_confirm_email_w_non_existing_auth_key(
self,
): # pylint: disable=invalid-name
""" """
Test confirmation with inexisting auth key Test confirmation with non existing auth key
""" """
self.login() self.login()
# Avoid sending out mails # Avoid sending out mails
@@ -264,7 +269,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
self.assertEqual( self.assertEqual(
str(list(response.context[0]["messages"])[-1]), str(list(response.context[0]["messages"])[-1]),
"Verification key does not exist", "Verification key does not exist",
"Confirm w/o inexisting key does not produce error message?", "Confirm w/o non existing key does not produce error message?",
) )
def test_remove_confirmed_email(self): def test_remove_confirmed_email(self):
@@ -352,7 +357,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
response = self.client.post( response = self.client.post(
reverse("add_email"), reverse("add_email"),
{ {
"email": "oliver@linux-kernel.at", # Whohu, static :-[ "email": "oliver@linux-kernel.at", # Wow, static :-[
}, },
) # Create test address ) # Create test address
unconfirmed = self.user.unconfirmedemail_set.first() unconfirmed = self.user.unconfirmedemail_set.first()
@@ -418,7 +423,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
"Photo deletion did not work?", "Photo deletion did not work?",
) )
def test_delete_inexisting_photo(self): def test_delete_non_existing_photo(self):
""" """
test deleting the photo test deleting the photo
""" """
@@ -602,22 +607,21 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
}, },
follow=True, follow=True,
) )
if test_only_one: if not test_only_one:
self.assertEqual(
self.user.photo_set.count(), 1, "there must be exactly one photo now!"
)
self.assertEqual(
str(list(response.context[0]["messages"])[-1]),
"Successfully uploaded",
"A valid image should return a success message!",
)
self.assertEqual(
self.user.photo_set.first().format,
"png",
"Format must be png, since we uploaded a png!",
)
else:
return response return response
self.assertEqual(
self.user.photo_set.count(), 1, "there must be exactly one photo now!"
)
self.assertEqual(
str(list(response.context[0]["messages"])[-1]),
"Successfully uploaded",
"A valid image should return a success message!",
)
self.assertEqual(
self.user.photo_set.first().format,
"png",
"Format must be png, since we uploaded a png!",
)
def test_upload_too_many_images(self): def test_upload_too_many_images(self):
""" """
@@ -741,7 +745,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
email=self.user.confirmedemail_set.first().email, email=self.user.confirmedemail_set.first().email,
) )
) )
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual(response.status_code, 200, "unable to fetch avatar?") self.assertEqual(response.status_code, 200, "unable to fetch avatar?")
@@ -782,7 +786,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
email=self.user.confirmedemail_set.first().email, email=self.user.confirmedemail_set.first().email,
) )
) )
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual(response.status_code, 200, "unable to fetch avatar?") self.assertEqual(response.status_code, 200, "unable to fetch avatar?")
@@ -823,7 +827,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
email=self.user.confirmedemail_set.first().email, email=self.user.confirmedemail_set.first().email,
) )
) )
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual(response.status_code, 200, "unable to fetch avatar?") self.assertEqual(response.status_code, 200, "unable to fetch avatar?")
@@ -969,7 +973,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
"Assign non existing photo, does not return error message?", "Assign non existing photo, does not return error message?",
) )
def test_assign_photo_to_inexisting_mail(self): # pylint: disable=invalid-name def test_assign_photo_to_non_existing_mail(self): # pylint: disable=invalid-name
""" """
Test if assigning photo to mail address that doesn't exist returns Test if assigning photo to mail address that doesn't exist returns
the correct error message the correct error message
@@ -990,9 +994,9 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
"Assign non existing photo, does not return error message?", "Assign non existing photo, does not return error message?",
) )
def test_import_photo_with_inexisting_email(self): # pylint: disable=invalid-name def test_import_photo_with_non_existing_email(self): # pylint: disable=invalid-name
""" """
Test if import with inexisting mail address returns Test if import with non existing mail address returns
the correct error message the correct error message
""" """
self.login() self.login()
@@ -1002,7 +1006,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
self.assertEqual( self.assertEqual(
str(list(response.context[0]["messages"])[0]), str(list(response.context[0]["messages"])[0]),
"Address does not exist", "Address does not exist",
"Import photo with inexisting mail id,\ "Import photo with non existing mail id,\
does not return error message?", does not return error message?",
) )
@@ -1022,10 +1026,24 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
should return an error message!", should return an error message!",
) )
def _manual_confirm(self):
"""
Helper method to confirm manually, because testing is really hard
"""
# Manual confirm, since testing is _really_ hard!
unconfirmed = self.user.unconfirmedopenid_set.first()
confirmed = ConfirmedOpenId()
confirmed.user = unconfirmed.user
confirmed.ip_address = "127.0.0.1"
confirmed.openid = unconfirmed.openid
confirmed.save()
unconfirmed.delete()
def test_add_openid(self, confirm=True): def test_add_openid(self, confirm=True):
""" """
Test if adding an OpenID works Test if adding an OpenID works
""" """
self.login() self.login()
# Get page # Get page
response = self.client.get(reverse("add_openid")) response = self.client.get(reverse("add_openid"))
@@ -1042,14 +1060,9 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
self.assertEqual(response.status_code, 302, "OpenID must redirect") self.assertEqual(response.status_code, 302, "OpenID must redirect")
if confirm: if confirm:
# Manual confirm, since testing is _really_ hard! self._manual_confirm()
unconfirmed = self.user.unconfirmedopenid_set.first()
confirmed = ConfirmedOpenId() # TODO Rename this here and in `test_add_openid`
confirmed.user = unconfirmed.user
confirmed.ip_address = "127.0.0.1"
confirmed.openid = unconfirmed.openid
confirmed.save()
unconfirmed.delete()
def test_add_openid_twice(self): def test_add_openid_twice(self):
""" """
@@ -1215,7 +1228,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
"Assign non existing photo, does not return error message?", "Assign non existing photo, does not return error message?",
) )
def test_assign_photo_to_openid_inexisting_openid( def test_assign_photo_to_openid_non_existing_openid(
self, self,
): # pylint: disable=invalid-name ): # pylint: disable=invalid-name
""" """
@@ -1292,7 +1305,9 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
"Removing unconfirmed mail does not work?", "Removing unconfirmed mail does not work?",
) )
def test_remove_unconfirmed_inexisting_openid(self): # pylint: disable=invalid-name def test_remove_unconfirmed_non_existing_openid(
self,
): # pylint: disable=invalid-name
""" """
Remove unconfirmed openid that doesn't exist Remove unconfirmed openid that doesn't exist
""" """
@@ -1305,7 +1320,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
self.assertEqual( self.assertEqual(
str(list(response.context[0]["messages"])[0]), str(list(response.context[0]["messages"])[0]),
"ID does not exist", "ID does not exist",
"Removing an inexisting openid should return an error message", "Removing an non existing openid should return an error message",
) )
def test_openid_redirect_view(self): def test_openid_redirect_view(self):
@@ -1353,7 +1368,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
size=size[0], size=size[0],
) )
) )
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual(response.status_code, 200, "unable to fetch avatar?") self.assertEqual(response.status_code, 200, "unable to fetch avatar?")
photodata = Image.open(BytesIO(response.content)) photodata = Image.open(BytesIO(response.content))
@@ -1370,15 +1385,15 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
size=80, size=80,
) )
) )
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual(response.status_code, 200, "unable to fetch avatar?") self.assertEqual(response.status_code, 200, "unable to fetch avatar?")
photodata = Image.open(BytesIO(response.content)) photodata = Image.open(BytesIO(response.content))
self.assertEqual(photodata.size, (80, 80), "Why is this not the correct size?") self.assertEqual(photodata.size, (80, 80), "Why is this not the correct size?")
def test_avatar_url_inexisting_mail_digest(self): # pylint: disable=invalid-name def test_avatar_url_non_existing_mail_digest(self): # pylint: disable=invalid-name
""" """
Test fetching avatar via inexisting mail digest Test fetching avatar via non existing mail digest
""" """
self.test_upload_image() self.test_upload_image()
self.test_confirm_email() self.test_confirm_email()
@@ -1394,11 +1409,11 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
digest = hashlib.md5(addr.strip().lower().encode("utf-8")).hexdigest() digest = hashlib.md5(addr.strip().lower().encode("utf-8")).hexdigest()
self.user.confirmedemail_set.first().delete() self.user.confirmedemail_set.first().delete()
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual( self.assertEqual(
response.redirect_chain[0][0], response.redirect_chain[0][0],
"/gravatarproxy/%s?s=80" % digest, f"/gravatarproxy/{digest}?s=80",
"Doesn't redirect to Gravatar?", "Doesn't redirect to Gravatar?",
) )
self.assertEqual( self.assertEqual(
@@ -1406,7 +1421,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
) )
self.assertEqual( self.assertEqual(
response.redirect_chain[1][0], response.redirect_chain[1][0],
"/avatar/%s?s=80&forcedefault=y" % digest, f"/avatar/{digest}?s=80&forcedefault=y",
"Doesn't redirect with default forced on?", "Doesn't redirect with default forced on?",
) )
self.assertEqual( self.assertEqual(
@@ -1424,11 +1439,11 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
# ) # )
# Eventually one should check if the data is the same # Eventually one should check if the data is the same
def test_avatar_url_inexisting_mail_digest_gravatarproxy_disabled( def test_avatar_url_non_existing_mail_digest_gravatarproxy_disabled(
self, self,
): # pylint: disable=invalid-name ): # pylint: disable=invalid-name
""" """
Test fetching avatar via inexisting mail digest Test fetching avatar via non existing mail digest
""" """
self.test_upload_image() self.test_upload_image()
self.test_confirm_email() self.test_confirm_email()
@@ -1441,7 +1456,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
# Simply delete it, then it digest is 'correct', but # Simply delete it, then it digest is 'correct', but
# the hash is no longer there # the hash is no longer there
self.user.confirmedemail_set.first().delete() self.user.confirmedemail_set.first().delete()
url = "%s?%s&gravatarproxy=n" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}&gravatarproxy=n"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual( self.assertEqual(
response.redirect_chain[0][0], response.redirect_chain[0][0],
@@ -1456,11 +1471,11 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
# ) # )
# Eventually one should check if the data is the same # Eventually one should check if the data is the same
def test_avatar_url_inexisting_mail_digest_w_default_mm( def test_avatar_url_non_existing_mail_digest_w_default_mm(
self, self,
): # pylint: disable=invalid-name ): # pylint: disable=invalid-name
""" """
Test fetching avatar via inexisting mail digest and default 'mm' Test fetching avatar via non existing mail digest and default 'mm'
""" """
urlobj = urlsplit( urlobj = urlsplit(
libravatar_url( libravatar_url(
@@ -1469,14 +1484,14 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
default="mm", default="mm",
) )
) )
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
self.client.get(url, follow=False) self.client.get(url, follow=False)
def test_avatar_url_inexisting_mail_digest_w_default_mm_gravatarproxy_disabled( def test_avatar_url_non_existing_mail_digest_w_default_mm_gravatarproxy_disabled(
self, self,
): # pylint: disable=invalid-name ): # pylint: disable=invalid-name
""" """
Test fetching avatar via inexisting mail digest and default 'mm' Test fetching avatar via non existing mail digest and default 'mm'
""" """
urlobj = urlsplit( urlobj = urlsplit(
libravatar_url( libravatar_url(
@@ -1485,7 +1500,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
default="mm", default="mm",
) )
) )
url = "%s?%s&gravatarproxy=n" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}&gravatarproxy=n"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual( self.assertEqual(
response.redirect_chain[0][0], response.redirect_chain[0][0],
@@ -1500,11 +1515,11 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
# ) # )
# Eventually one should check if the data is the same # Eventually one should check if the data is the same
def test_avatar_url_inexisting_mail_digest_wo_default( def test_avatar_url_non_existing_mail_digest_wo_default(
self, self,
): # pylint: disable=invalid-name ): # pylint: disable=invalid-name
""" """
Test fetching avatar via inexisting mail digest and default 'mm' Test fetching avatar via non existing mail digest and default 'mm'
""" """
urlobj = urlsplit( urlobj = urlsplit(
libravatar_url( libravatar_url(
@@ -1513,11 +1528,11 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
) )
) )
digest = hashlib.md5("asdf@company.local".lower().encode("utf-8")).hexdigest() digest = hashlib.md5("asdf@company.local".lower().encode("utf-8")).hexdigest()
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual( self.assertEqual(
response.redirect_chain[0][0], response.redirect_chain[0][0],
"/gravatarproxy/%s?s=80" % digest, f"/gravatarproxy/{digest}?s=80",
"Doesn't redirect to Gravatar?", "Doesn't redirect to Gravatar?",
) )
self.assertEqual( self.assertEqual(
@@ -1525,7 +1540,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
) )
self.assertEqual( self.assertEqual(
response.redirect_chain[1][0], response.redirect_chain[1][0],
"/avatar/%s?s=80&forcedefault=y" % digest, f"/avatar/{digest}?s=80&forcedefault=y",
"Doesn't redirect with default forced on?", "Doesn't redirect with default forced on?",
) )
self.assertEqual( self.assertEqual(
@@ -1544,11 +1559,11 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
# ) # )
# Eventually one should check if the data is the same # Eventually one should check if the data is the same
def test_avatar_url_inexisting_mail_digest_wo_default_gravatarproxy_disabled( def test_avatar_url_non_existing_mail_digest_wo_default_gravatarproxy_disabled(
self, self,
): # pylint: disable=invalid-name ): # pylint: disable=invalid-name
""" """
Test fetching avatar via inexisting mail digest and default 'mm' Test fetching avatar via non existing mail digest and default 'mm'
""" """
urlobj = urlsplit( urlobj = urlsplit(
libravatar_url( libravatar_url(
@@ -1556,7 +1571,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
size=80, size=80,
) )
) )
url = "%s?%s&gravatarproxy=n" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}&gravatarproxy=n"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual( self.assertEqual(
response.redirect_chain[0][0], response.redirect_chain[0][0],
@@ -1582,7 +1597,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
default="/static/img/nobody.png", default="/static/img/nobody.png",
) )
) )
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
url += "&gravatarproxy=n" url += "&gravatarproxy=n"
response = self.client.get(url, follow=False) response = self.client.get(url, follow=False)
self.assertEqual(response.status_code, 302, "Doesn't redirect with 302?") self.assertEqual(response.status_code, 302, "Doesn't redirect with 302?")
@@ -1605,7 +1620,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
default="/static/img/nobody.png", default="/static/img/nobody.png",
) )
) )
url = "%s?%s&gravatarproxy=n" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}&gravatarproxy=n"
response = self.client.get(url, follow=True) response = self.client.get(url, follow=True)
self.assertEqual( self.assertEqual(
response.redirect_chain[0][0], response.redirect_chain[0][0],
@@ -1627,11 +1642,11 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
default=default, default=default,
) )
) )
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
response = self.client.get(url, follow=False) response = self.client.get(url, follow=False)
self.assertRedirects( self.assertRedirects(
response=response, response=response,
expected_url="/gravatarproxy/fb7a6d7f11365642d44ba66dc57df56f?s=%s" % size, expected_url=f"/gravatarproxy/fb7a6d7f11365642d44ba66dc57df56f?s={size}",
fetch_redirect_response=False, fetch_redirect_response=False,
msg_prefix="Why does this not redirect to the default img?", msg_prefix="Why does this not redirect to the default img?",
) )
@@ -1648,7 +1663,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
default=default, default=default,
) )
) )
url = "%s?%s" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}"
response = self.client.get(url, follow=False) response = self.client.get(url, follow=False)
self.assertRedirects( self.assertRedirects(
response=response, response=response,
@@ -1672,7 +1687,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
default=default, default=default,
) )
) )
url = "%s?%s&gravatarproxy=n" % (urlobj.path, urlobj.query) url = f"{urlobj.path}?{urlobj.query}&gravatarproxy=n"
response = self.client.get(url, follow=False) response = self.client.get(url, follow=False)
self.assertRedirects( self.assertRedirects(
response=response, response=response,
@@ -1748,14 +1763,14 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
reverse("password_change"), reverse("password_change"),
{ {
"old_password": self.password, "old_password": self.password,
"new_password1": self.password + ".", "new_password1": f"{self.password}.",
"new_password2": self.password, "new_password2": self.password,
}, },
follow=True, follow=True,
) )
self.assertContains( self.assertContains(
response, response,
"The two password fields didn", "The two password fields did",
1, 1,
200, 200,
"Old password was entered incorrectly, site should raise an error", "Old password was entered incorrectly, site should raise an error",
@@ -1771,14 +1786,14 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
{ {
"old_password": self.password, "old_password": self.password,
"new_password1": self.password, "new_password1": self.password,
"new_password2": self.password + ".", "new_password2": f"{self.password}.",
}, },
follow=True, follow=True,
) )
self.assertContains( self.assertContains(
response, response,
"The two password fields didn", "The two password fields did",
1, 1,
200, 200,
"Old password as entered incorrectly, site should raise an error", "Old password as entered incorrectly, site should raise an error",
@@ -1829,7 +1844,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
) )
self.assertContains( self.assertContains(
response, response,
self.first_name + " " + self.last_name, f"{self.first_name} {self.last_name}",
1, 1,
200, 200,
"First and last name not correctly listed in profile page", "First and last name not correctly listed in profile page",
@@ -2047,7 +2062,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
"Upload didn't work?", "Upload didn't work?",
) )
def test_prefs_page(self): def test_preferences_page(self):
""" """
Test if preferences page works Test if preferences page works
""" """
@@ -2080,7 +2095,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
# Create a second user that will conflict # Create a second user that will conflict
user2 = User.objects.create_user( user2 = User.objects.create_user(
username=self.username + "1", username=f"{self.username}1",
password=self.password, password=self.password,
first_name=self.first_name, first_name=self.first_name,
last_name=self.last_name, last_name=self.last_name,
@@ -2097,12 +2112,9 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
"Mail not the same?", "Mail not the same?",
) )
# This needs to be cought # This needs to be caught
try: with contextlib.suppress(AssertionError):
self.test_confirm_email() self.test_confirm_email()
except AssertionError:
pass
# Request a random page, so we can access the messages # Request a random page, so we can access the messages
response = self.client.get(reverse("profile")) response = self.client.get(reverse("profile"))
self.assertEqual( self.assertEqual(

View File

@@ -2,6 +2,9 @@
""" """
Test our views in ivatar.ivataraccount.views and ivatar.views Test our views in ivatar.ivataraccount.views and ivatar.views
""" """
import contextlib
# pylint: disable=too-many-lines # pylint: disable=too-many-lines
import os import os
import django import django
@@ -63,28 +66,24 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
""" """
Create a confirmed openid Create a confirmed openid
""" """
confirmed = ConfirmedOpenId.objects.create( return ConfirmedOpenId.objects.create(
user=self.user, user=self.user,
ip_address="127.0.0.1", ip_address="127.0.0.1",
openid=self.openid, openid=self.openid,
) )
return confirmed
def create_confirmed_email(self): def create_confirmed_email(self):
""" """
Create a confirmed email Create a confirmed email
""" """
confirmed = ConfirmedEmail.objects.create( return ConfirmedEmail.objects.create(
email=self.email, email=self.email,
user=self.user, user=self.user,
) )
return confirmed
# The following tests need to be moved over to the model tests # The following tests need to be moved over to the model tests
# and real web UI tests added # and real web UI tests added
def test_bluesky_handle_for_mail_via_model_handle_doesnt_exist(self): def test_bluesky_handle_for_mail_via_model_handle_does_not_exist(self):
""" """
Add Bluesky handle to a confirmed mail address Add Bluesky handle to a confirmed mail address
""" """
@@ -92,14 +91,12 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
confirmed = self.create_confirmed_email() confirmed = self.create_confirmed_email()
confirmed.set_bluesky_handle(self.bsky_test_account) confirmed.set_bluesky_handle(self.bsky_test_account)
try: with contextlib.suppress(Exception):
confirmed.set_bluesky_handle(self.bsky_test_account + "1") confirmed.set_bluesky_handle(f"{self.bsky_test_account}1")
except Exception:
pass
self.assertNotEqual( self.assertNotEqual(
confirmed.bluesky_handle, confirmed.bluesky_handle,
self.bsky_test_account + "1", f"{self.bsky_test_account}1",
"Setting Bluesky handle that doesn exist works?", "Setting Bluesky handle that doesn't exist works?",
) )
def test_bluesky_handle_for_mail_via_model_handle_exists(self): def test_bluesky_handle_for_mail_via_model_handle_exists(self):
@@ -116,7 +113,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
"Setting Bluesky handle doesn't work?", "Setting Bluesky handle doesn't work?",
) )
def test_bluesky_handle_for_openid_via_model_handle_doesnt_exist(self): def test_bluesky_handle_for_openid_via_model_handle_does_not_exist(self):
""" """
Add Bluesky handle to a confirmed openid address Add Bluesky handle to a confirmed openid address
""" """
@@ -124,14 +121,12 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
confirmed = self.create_confirmed_openid() confirmed = self.create_confirmed_openid()
confirmed.set_bluesky_handle(self.bsky_test_account) confirmed.set_bluesky_handle(self.bsky_test_account)
try: with contextlib.suppress(Exception):
confirmed.set_bluesky_handle(self.bsky_test_account + "1") confirmed.set_bluesky_handle(f"{self.bsky_test_account}1")
except Exception:
pass
self.assertNotEqual( self.assertNotEqual(
confirmed.bluesky_handle, confirmed.bluesky_handle,
self.bsky_test_account + "1", f"{self.bsky_test_account}1",
"Setting Bluesky handle that doesn exist works?", "Setting Bluesky handle that doesn't exist works?",
) )
def test_bluesky_handle_for_openid_via_model_handle_exists(self): def test_bluesky_handle_for_openid_via_model_handle_exists(self):
@@ -161,7 +156,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
response = self.client.get(lu) response = self.client.get(lu)
# This is supposed to redirect to the Bluesky proxy # This is supposed to redirect to the Bluesky proxy
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertEqual(response["Location"], "/blueskyproxy/%s" % confirmed.digest) self.assertEqual(response["Location"], f"/blueskyproxy/{confirmed.digest}")
def test_bluesky_fetch_openid(self): def test_bluesky_fetch_openid(self):
""" """
@@ -176,7 +171,7 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
response = self.client.get(lu) response = self.client.get(lu)
# This is supposed to redirect to the Bluesky proxy # This is supposed to redirect to the Bluesky proxy
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertEqual(response["Location"], "/blueskyproxy/%s" % confirmed.digest) self.assertEqual(response["Location"], f"/blueskyproxy/{confirmed.digest}")
def test_assign_bluesky_handle_to_openid(self): def test_assign_bluesky_handle_to_openid(self):
""" """

View File

@@ -2,6 +2,9 @@
""" """
Test our views in ivatar.ivataraccount.views and ivatar.views Test our views in ivatar.ivataraccount.views and ivatar.views
""" """
import contextlib
# pylint: disable=too-many-lines # pylint: disable=too-many-lines
import os import os
import json import json
@@ -14,11 +17,8 @@ from ivatar.utils import random_string, Bluesky
BLUESKY_APP_PASSWORD = None BLUESKY_APP_PASSWORD = None
BLUESKY_IDENTIFIER = None BLUESKY_IDENTIFIER = None
try: with contextlib.suppress(Exception):
from settings import BLUESKY_APP_PASSWORD, BLUESKY_IDENTIFIER from settings import BLUESKY_APP_PASSWORD, BLUESKY_IDENTIFIER
except Exception: # pylint: disable=broad-except
pass
os.environ["DJANGO_SETTINGS_MODULE"] = "ivatar.settings" os.environ["DJANGO_SETTINGS_MODULE"] = "ivatar.settings"
django.setup() django.setup()
@@ -56,16 +56,16 @@ class Tester(TestCase): # pylint: disable=too-many-public-methods
""" """
Test incorrect digest Test incorrect digest
""" """
response = self.client.get("/avatar/%s" % "x" * 65, follow=True) response = self.client.get("/avatar/" + "x" * 65, follow=True)
self.assertEqual( self.assertEqual(
response.redirect_chain[0][0], response.redirect_chain[2][0],
"/static/img/deadbeef.png", "/static/img/nobody/80.png",
"Doesn't redirect to static?", "Doesn't redirect to static?",
) )
# self.assertRedirects( # self.assertRedirects(
# response=response, # response=response,
# expected_url="/static/img/deadbeef.png", # expected_url="/static/img/nobody/80.png",
# msg_prefix="Why does an invalid hash not redirect to deadbeef?", # msg_prefix="Why does an invalid hash not redirect to deadbeef?",
# ) # )
def test_stats(self): def test_stats(self):