Can't Test Password Change In Django Unittest
Solution 1:
I was using dev server to run unittests. When I changed my password, I was actually posting to the dev server instead of the test one.
Here is my new unittest
import json
from django.contrib.auth.models import User
from django.test import Client
from django.test import TestCase
from adaptors.redis_class import DjangoRedis
class PasswordChange(TestCase):
def setUp(self):
User.objects.create_user(username='john', email='john@john.com', password='john')
r = DjangoRedis()
r.set("email:john@john.com", '0' * 40, ex=3600)
r.set('0' * 40, "email:john@john.com", ex=3600)
def test_change_password(self):
c = Client()
payload = {'payload': json.dumps({'password': 'johnjohn'})}
url = '/reset/' + '0' * 40 + '/'
res = c.post(url, payload)
res = res.json()
self.assertEqual(res['password_changed'], True)
u = User.objects.get(username='john')
self.assertEqual(u.check_password('johnjohn'), True)
If you're going to use selenium
IDE, make sure you inherent from StaticLiveServerTestCase
instead of unittest. Follow this example. Also, don't forget to change this variable self.base_url
to self.live_server_url
This inside my setUp method
self.base_url = self.live_server_url
Thanks to fips, koterpillar for helping me on the IRC channel, and aks for commenting under me.
Solution 2:
You are not making an http post
as your view expects.
Here is how to make a post using urllib2: Making a POST call instead of GET using urllib2
But, since you already use requests
module why not simply do:
url = 'http://127.0.0.1:8000/reset/' + '0' * 40 + '/'
payload = {'csrfmiddlewaretoken': csrf_token, 'payload': json.dumps({'password': 'johnjohn'})}
headers = {'Cookie': 'csrftoken=' + csrf_token}
r = requests.post(url, data=payload, headers=headers)
json_res = json.loads(r.content)
And maybe try debugging/printing the value of json_res
to check if there's anything else unexpected.
Also note, this is an integration test as you are testing through http, so your urls.py, views.py and even settings.py are being tested as part of it.
Post a Comment for "Can't Test Password Change In Django Unittest"