Last active
July 13, 2018 12:09
-
-
Save eeriksp/09b4ce1f6847e9d5c1a7de98d0cf890c to your computer and use it in GitHub Desktop.
A TestCase for Django admin, witch checks whether all admin pages work.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from django.test import TestCase, Client | |
from django.contrib.auth.models import User | |
LINK_PATTERN = re.compile(r'<a href="(/admin/[^ ]+)"') | |
class TestDjangoAdmin(TestCase): | |
def test_if_admin_pages_work(self): | |
""" | |
If there is something wrong with migrations, | |
related admin pages are not accessable. | |
Checking whether the admin pages work is thus | |
a good opportunity to control whether | |
the structure of the database is OK. | |
""" | |
# Create user and log in | |
password = 'adminadminadmin' | |
user = User.objects.create_superuser('myuser', '[email protected]', password) | |
client = Client() | |
login = client.login(username=user.username, password=password) | |
self.assertEqual(login, True) | |
# Go to admin homepage | |
homepage_response = client.get('/haldus/') | |
self.assertEqual(homepage_response.status_code, 200) | |
# # Find all links on that page | |
html = homepage_response.content.decode('utf-8') | |
matches = LINK_PATTERN.finditer(html) | |
# Clear results to get URLs | |
# There are a lot duplicate URLs on the page. To remove them, we use a set instead of a list. | |
# We do not want to change password or log out, therefore theese URLs are excluded. | |
urls = {match.groups()[0] for match in matches} - {'/haldus/password_change/', '/haldus/logout/'} | |
# Visit URLs and check response.status_code | |
for url in urls: | |
response = client.get(url) | |
self.assertEqual(response.status_code, 200, msg=f"This url cannot be accessed: '{url}'") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment