Skip to content

Instantly share code, notes, and snippets.

@raiderrobert
Created May 31, 2016 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raiderrobert/615dfd0cee6465d799ce38e5f0e736a6 to your computer and use it in GitHub Desktop.
Save raiderrobert/615dfd0cee6465d799ce38e5f0e736a6 to your computer and use it in GitHub Desktop.
Testing Views in Django With Hypothesis
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from hypothesis import given, strategies as st
from .models import User
class ViewsTestCase(TestCase):
PUBLIC_URLS = ['login', ]
PRIVATE_URLS = ['dashboard', 'user_list', 'user_add', ]
def setUp(self):
self.c = Client()
def assert_redirect_to_page(self, page_reverse_string, redirect_reverse_string, next_in_url=True):
response = self.c.get(reverse(page_reverse_string))
redirect_url = reverse(redirect_reverse_string)
if next_in_url:
redirect_url += "?next=" + reverse(page_reverse_string)
self.assertRedirects(response, redirect_url)
def assert_200_response_code(self, page_reverse_string):
response = self.c.get(reverse(page_reverse_string))
self.assertEquals(response.status_code, 200)
class AnonymousUserViewsTests(ViewsTestCase):
@given(url_name=st.sampled_from(ViewsTestCase.PUBLIC_URLS))
def test_public_urls(self, url_name):
self.assert_200_response_code(url_name)
@given(url_name=st.sampled_from(ViewsTestCase.PRIVATE_URLS))
def test_private_urls(self, url_name):
self.assert_redirect_to_page(url_name, 'login')
class LoggedInUserViewsTests(ViewsTestCase):
def setUp(self):
super(LoggedInUserViewsTests, self).setUp()
self.user = User.objects.create_superuser(username='email@email.com', password='password')
self.c.login(username='email@email.com', password='password')
@given(url_name=st.sampled_from(ViewsTestCase.PUBLIC_URLS))
def test_public_urls(self, url_name):
self.assert_200_response_code(url_name)
@given(url_name=st.sampled_from(ViewsTestCase.PRIVATE_URLS))
def test_public_urls(self, url_name):
self.assert_200_response_code(url_name)
@kevinmarsh
Copy link

Hi Robert, nice accompanying article, but I think you've accidentally defined LoggedInUserViewsTests.test_public_urls twice instead of test_private_urls

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment