Reputation: 2886
I have a django app I wanted to write tests for. For now Im writing integration tests for the urls.
For my signin
test , my url looks like:
url(r'^signin/$', login_forbidden(signin), name='signin')
and my test looks like:
from django.test import TestCase
class SigninTest(TestCase):
def test_signin(self):
resp = self.client.get('/signin/')
self.assertEqual(resp.status_code, 200)
However I have no idea to test a a longer url, for instance I have one entry in urls like:
url(
r'^ad_accounts/(?P<ad_account_id>[^/]+)/$',
AdAccountDetailView.as_view(),
name='campaigns'
),
If I repeat the above test I have for the signin page (replacing resp = self.client.get('/ad_accounts/')
) returns a failure
======================================================================
FAIL: test_signin (engineoftravel.tests.SigninTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "path/to/project/tests.py", line 7, in test_signin
self.assertEqual(resp.status_code, 200)
AssertionError: 302 != 200
----------------------------------------------------------------------
Ran 1 test in 0.103s
FAILED (failures=1)
Upvotes: 0
Views: 429
Reputation: 921
For the test failure, you should first login with some test user then make a request, otherwise the page will be redirected to the login page and thus you will get a 302 status code.
Also you can test the status code of the redirected page with client.get('/foo', follow=True)
which returns the status code of the sign in page. (In your example)
Upvotes: 0
Reputation:
from django.test import TestCase
from django.test import Client
from django.core.urlresolvers import reverse
client = Client()
class MainTest(TestCase):
##user login in django
def user_login(self, username, password):
response = self.client.login(username=username, password=username)
return self.assertEqual(resp.status_code, 200)
## first case
def detail(self):
response = self.client.get('/ad_accounts/<test_num>/') ## url regex
self.assertEquals(response.status_code, 200)
def detail2(self):
response = self.client.get(reverse('campaigns'))
self.assertEqual(response.status_code, 200)
Upvotes: 0
Reputation: 151
why not use reverse: https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#reverse
from django.core.urlresolvers import reverse
....
resp = self.client.get(reverse('campaigns', args=[1]))
where args is the id you need to pass in.
EDIT: since django 1.10 reverse imports from django.urls
Upvotes: 1