Reputation: 3008
I am trying to test revoke function in the view:
@login_required
def revoke(request, id):
"""
Delete access token
"""
obj = Hiren.objects.get(pk=id)
obj.delete()
return redirect('/hiren')
Here is my test code that throws an error:
class TestRevokeView(TestCase):
def setUp(self):
User.objects.create_superuser(
username='admin', password='admin', email='[email protected]')
item = Hiren()
item.access_token = "bla bla"
item.authorized = True
item.save()
def test_logged_in_user_can_delete_object(self):
self.client.login(username='admin', password='admin')
count = Hiren.objects.all().count()
self.assertEqual(count, 1)
response = self.client.get('/revoke/1/', follow=True)
self.assertRedirects(response, '/hiren/')
Here is the error code:
Traceback (most recent call last):
File ".....tests.py", line 109, in test_logged_in_user_can_delete_object
response = self.client.get('/revoke/1/', follow=True)
....................
self.model._meta.object_name
github.models.DoesNotExist: Hiren matching query does not exist.
So my question is what I am missing here.
Upvotes: 0
Views: 2601
Reputation: 2569
Probabily, the pk
of Hiren
item is not 1.
class TestRevokeView(TestCase):
def setUp(self):
User.objects.create_superuser(
username='admin', password='admin', email='[email protected]')
self.item = Hiren()
self.item.access_token = "bla bla"
self.item.authorized = True
self.item.save()
def test_logged_in_user_can_delete_object(self):
self.client.login(username='admin', password='admin')
count = Hiren.objects.all().count()
self.assertEqual(count, 1)
response = self.client.get('/revoke/{0}/'.format(self.item.pk), follow=True)
self.assertRedirects(response, '/hiren/')
Upvotes: 2
Reputation: 22697
You need to be sure that Hiren
instance that you created on setUp
method, has ID
equal to 1
To avoid that, set Hiren
id instance a class variable and then use it on your test method.
class TestRevokeView(TestCase):
def setUp(self):
User.objects.create_superuser(
username='admin', password='admin', email='[email protected]')
item = Hiren()
item.access_token = "bla bla"
item.authorized = True
item.save()
self.HIREN_ID = item.id
def test_logged_in_user_can_delete_object(self):
self.client.login(username='admin', password='admin')
count = Hiren.objects.all().count()
self.assertEqual(count, 1)
response = self.client.get('/revoke/%s/' % self.HIREN_ID), follow=True)
self.assertRedirects(response, '/hiren/')
Upvotes: 3