How to test PasswordChangeView in Django? - django

I'm trying to create a test for the get_success_url method of PasswordChangeView to see whether the redirect work as intended.
The expected behavior I'm looking for -- with a valid form -- is to have the password changed, and to get a 302 redirect response.
But for some unknown reason, I can't seem to pass valid form data, so I get a 200 response, and the test keeps failing.
Does anyone know why the test below gives me an invalid form? What am I missing?
test.py
def test_success_url(self):
client = Client()
user = User.objects.create(username="anon", password="pw")
client.force_login(user)
data = {
'old_password': 'pw',
'new_password1': 'newpw',
'new_password2': 'newpw',
}
response = client.post('/anon/change-password/', data)
user.refresh_from_db()
self.assertTrue(user.check_password('newpw))
self.assertEqual(response, 302)
views.py
class UserPasswordChangeView(LoginRequiredMixin, PermissionMixin, PasswordChangeView):
def get_success_url(self):
return reverse("user:detail", kwargs={ "username": self.request.user })

You should use create_user to create your user object, not create.
user = User.objects.create_user(username="anon", password="pw")

Related

Django request.POST returning NONE

I have been working on a Django REST API and one of the views is as follows :
#api_view(['POST'])
def create(request):
key = request.POST.get('key')
name = request.POST.get("name")
email = request.POST.get("email")
password = request.POST.get("password")
print(key)
if(key=='0'):
user = Users(name=name,email=email,password=password)
user.save()
return Response("User Created Successfully")
else:
return Response("Invalid Key")
When I send a POST request with all the proper parameters I get the key printed as NONE, but I tried replacing POST with GET every where as below and then sending a GET request actually works normally, but POST request isn't working :
#api_view(['GET'])
def create(request):
key = request.GET.get('key')
name = request.GET.get("name")
email = request.GET.get("email")
password = request.GET.get("password")
print(key)
if(key=='0'):
user = Users(name=name,email=email,password=password)
user.save()
return Response("User Created Successfully")
else:
return Response("Invalid Key")
Thanks in advance !!
Tried GET instead of POST and that works, but since this is a method to enter value in the DB so this should be POST request.
[Edit 1]
I have tried using request.data but that isn't working, it is returning empty request like this {} and the same is the case with request.POST.
I am sending the request from Postman.
The request I am sending is like this :
In your screenshot, you are passing query parameters in POST request. You should POST data though data tab in postman (formdata,json,etc). Based on your screenshot, you can get the data passed through request.query_params, but this is not recommended for POST requests.
In Django REST Framework, request.POST or data submitted through POST is restructured into request.data and data through GET requests is passed into request.query_params. Both of these are QueryDict, so normal dictionary methods are applicable.
Reference: https://www.django-rest-framework.org/api-guide/requests/#request-parsing

Django, "render" returns a POST request and not GET after a POST request

I'm having my view
def my_wishlist(request):
user = request.user
user_products = WishlistProductPrices.objects.filter(user=user).all()
### Create filters ###
filter = get_user_filter_fields_wishlist(user_products)
filter = filter(request.GET,queryset = user_products)
if request.method == "POST":
post_form = MyForm(request.POST)
if post_form.is_valid():
#do stuff
form = MyForm()
context = {
"form":form,
"filter":filter
}
return render(request, "myapp/add_wishlist.html",context=context) #Returns POST, seems like
else:
#invalid post_form
context = {
"form":post_form,
"filter":filter
}
return render(request, "myapp/add_wishlist.html",context=context)
else: #Get request
form = MyForm()
context = {
"form":form,
"filter":filter
}
return render(request, "myapp/add_wishlist.html",context=context)
it works like a charm, but after the user has submitted something, and presses F5 the "do you want to resend the information again" pops-up.
I find it weird, since I assume the render(request,"mypp/add_wishlist.html) ad the bottom of the page would return a GET request?
render simply renders the template, and wraps this in a HttpResponse and returns that as response to the HTTP request, regardless what that request is.
This means that if the form is valid, and you render a response back, then refreshing will normally make the same HTTP request. This thus means that a person who makes an order can for example make a second order by just refreshing the webpage.
As a result in case of a successful request (so where the form is valid), one implements the Post/Redirect/Get architectural pattern [wiki]. In that case, it does not render a template, but it returns a redirect response (a response with status code 302), and thus asks the browser to make a GET request to the passed url.
You can make such redirect with the redirect(…) function [Django-doc].

Request method mapping is happening after permission check

I have a view that creates and updates user as shown below.
class UserViewSet(ViewSet):
def check_permissions(self, request):
print("Action = ", self.action)
if self.action == 'create_user':
return True
return super().check_permissions(request)
def create_user(self, request):
# user creation code
def update(self, request):
#user update code
And create_user is mapped with POST method and update is mapped with PUT method. So, create_user action should not require authenticated user but for update, user should be authenticated. Overriding check_permission did the job. Now, when I was testing the create_user end point. I wrote a test that tries to creates user using some method other than POST. I expected that the response should be HTTP_405_METHOD_NOT_ALLOWED.
def test_create_user_with_invalid_method(self):
data = self.user_data
response = self.client.put(self.url, data)
self.assertEqual(response.status_code, HTTP_405_METHOD_NOT_ALLOWED)
But the response was HTTP_401_UNAUTHORIZED. And the action variable was set as None. My url mapping is like this:
url(r'^account/register/$', UserViewSet.as_view({"post": "create_user"}),name="account_register_view"),
url(r'^account/update/$', UserViewSet.as_view({"put": "update"}), name="account_update_vew"),
So looking at this, I thought djago is either doing the mapping of request(method, url) to action either after checking permission or doing it before but setting action as None when it fails to find the proper mapping
So my concern is that whether this is the correct behaviour and the test i wrote and what i was expecting is wrong or is there something strange going on here.

Unable to redirect to #login_required URL in django_webtest case

I'm using django_webtest to test my application. I faced with problem when try to test sign-up page. This page should create user and make other initial actions, authenticate newly created user and redirect it to the page specified in next parameter of GET request.
Here is the code of view method:
def _redirect_path(referrer, restricted_paths=()):
if not referrer or referrer in (reverse(name) for name in restricted_paths):
return reverse('home')
else:
return referrer
...
def sign_up(request):
if request.user.is_authenticated():
return redirect(reverse('home'))
if request.method == 'POST':
form = forms.SignUpForm(request.POST)
if form.is_valid():
with transaction.commit_on_success():
user = form.save()
profile = Profile.objects.create(user=user)
tokens.create_token(profile, 'unsubscribe')
mail.send_welcome_letter(request, user)
messages.success(request, _('You have successfully signed up. Welcome!'))
authenticated_user = auth.authenticate(username=user.username, password=form.cleaned_data['password'])
if authenticated_user:
auth.login(request, authenticated_user)
remember_user(request, authenticated_user)
redirect_path = _redirect_path(form.clean_referrer(), ('password_reset', 'sign_up'))
return redirect(redirect_path)
else:
raise Exception("Newly created user couldn't be authenticated.")
else:
referrer = request.GET.get('next')
form = forms.SignUpForm(initial={'referrer': referrer})
return render_to_response('sign_up.html', {'form': form}, context_instance=RequestContext(request))
Now I try to test its behavior when user entered example.com/sign_up/?next=/settings/ in his browser, fill all fields of form correctly and submit it.
View that handles /settings/ has decorator #login_required, but after user is successfully signed up, he should be authenticated, so I expect that after submit user will go to example.com/settings/ (and he goes when I test it manually).
But when I run test:
def test_user_creation_redirect_to_settings(self):
form = self.app.get('/sign_up/', {'next': '/settings/'}).form
self.fill_sign_up_form(form)
submit_response = form.submit()
self.assertRedirects(submit_response, '/settings/')
it returns "AssertionError: Couldn't retrieve redirection page '/settings/': response code was 302 (expected 200)". When I debugged, I have seen that *submit_response* is really 302 FOUND with location path /settings/. But when method assertRedirects tries to get target page, it faces with redirect again - example.com/settings/ redirects to example.com/login/?next=/settings/. So user is not logged in after submit.
OK, I tried to log in him with test client's login method:
def test_user_creation_redirect_to_settings(self):
form = self.app.get('/sign_up/', {'next': '/settings/'}).form
self.fill_sign_up_form(form)
submit_response = form.submit()
submit_response.client.login(username='User', password='secret')
self.assertRedirects(submit_response, '/settings/')
But still the same. Seems, this method is not works:
def test_user_creation_redirect_to_settings(self):
form = self.app.get('/sign_up/', {'next': '/settings/'}).form
self.fill_sign_up_form(form)
submit_response = form.submit()
inside = self.client.login(username='User', password='secret')
print inside and 'Login successful in self client'
print 'Authenticated: %s' % bool('_auth_user_id' in self.client.session)
inside = submit_response.client.login(username='User', password='secret')
print inside and 'Login successful in response client'
print 'Authenticated: %s' % bool('_auth_user_id' in submit_response.client.session)
prints
Login successful in self client
Authenticated: True
Login successful in response client
Authenticated: False
Could you please help me to understand why login functionality doesn't work in test case and how to log in user before redirect.
Thanks!
Have you tried using the follow method in your tests? Doing so follows redirects.
form.submit().follow()
This is a django-webtest bug that was fixed in django-webtest 1.5.3.

django testing problems

This is my view that I want to be tested.
def logIn(request):
"""
This method will log in user using username or email
"""
if request.method == 'POST':
form = LogInForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['name'],password=form.cleaned_data['password'])
if user:
login(request,user)
return redirect('uindex')
else:
error = "Nie prawidlowy login lub haslo.Upewnij sie ze wpisales prawidlowe dane"
else:
form = LogInForm(auto_id=False)
return render_to_response('login.html',locals(),context_instance=RequestContext(request))
And here's the test
class LoginTest(unittest.TestCase):
def setUp(self):
self.client = Client()
def test_response_for_get(self):
response = self.client.get(reverse('logIn'))
self.assertEqual(response.status_code, 200)
def test_login_with_username(self):
"""
Test if user can login wit username and password
"""
user_name = 'test'
user_email = 'test#test.com'
user_password = 'zaq12wsx'
u = User.objects.create_user(user_name,user_email,user_password)
response = self.client.post(reverse('logIn'),data={'name':user_name,'password':user_password},follow=True)
self.assertEquals(response.request.user.username,user_name)
u.delete()
And when i run this test i got failure on test_login_with_username:
AttributeError: 'dict' object has no attribute 'user'
When i use in views request.user.username in works fine no error this just fails in tests. Thanks in advance for any help
edit:Ok I replace the broken part with
self.assertEquals(302, response.status_code)
But now this test breaks and another one too.
AssertionError: 302 != 200
Here is my code for the view that now fail. I want email and username to be unique.
def register(request):
"""
Function to register new user.
This function will have to care for email uniqueness,and login
"""
if request.method == 'POST':
error=[]
form = RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
if form.cleaned_data['password'] == form.cleaned_data['password_confirmation']:
password = form.cleaned_data['password']
if len(User.objects.filter(username=username)) == 0 and len(User.objects.filter(email=email)) == 0:
#email and username are bouth unique
u = User()
u.username = username
u.set_password(password)
u.email = email
u.is_active = False
u.is_superuser = False
u.is_active = True
u.save()
return render_to_response('success_register.html',locals(),context_instance=RequestContext(request))
else:
if len(User.objects.filter(username=username)) > 0:
error.append("Podany login jest juz zajety")
if len(User.objects.filter(email=email)) > 0:
error.append("Podany email jest juz zajety")
else:
error.append("Hasla nie pasuja do siebie")
#return render_to_response('register.html',locals(),context_instance=RequestContext(request))
else:
form = RegisterForm(auto_id=False)
return render_to_response('register.html',locals(),context_instance=RequestContext(request))
And here is the test that priviously work but now it is broken
def test_user_register_with_unique_data_and_permission(self):
"""
Will try to register user which provided for sure unique credentials
And also make sure that profile will be automatically created for him, and also that he he have valid privileges
"""
user_name = 'test'
user_email = 'test#test.com'
password = 'zaq12wsx'
response = self.client.post(reverse('register'),{'username': user_name,'email':user_email,
'password':password,'password_confirmation':password},follow=True)
#check if code is 200
self.assertEqual(response.status_code, 200)
u = User.objects.get(username=user_name,email = user_email)
self.assertTrue(u,"User after creation coudn't be fetched")
self.assertFalse(u.is_staff,msg="User after registration belong to staff")
self.assertFalse(u.is_superuser,msg="User after registration is superuser")
p = UserProfile.objects.get(user__username__iexact = user_name)
self.assertTrue(p,"After user creation coudn't fetch user profile")
self.assertEqual(len(response.context['error']),0,msg = 'We shoudnt get error during valid registration')
u.delete()
p.delete()
End here is the error:
AssertionError: We shoudnt get error during valid registration
If i disable login test everything is ok. How this test can break another one? And why login test is not passing. I try it on website and it works fine.
The documentation for the response object returned by the test client says this about the request attribute:
request
The request data that stimulated the response.
That suggests to me one of two things. Either it's just the data of the request, or it's request object as it was before you handled the request. In either case, you would not expect it to contain the logged in user.
Another way to write your test that the login completed successfully would be to add follow=False to the client.post call and check the response code:
self.assertEquals(302, response.status_code)
This checks that the redirect has occurred.
response.request is not the HttpRequest object in the view you are expecting. It's a dictionary of data that stimulated the post request. It doesn't have the user attribute, hence the AttributeError
You could rewrite your test to:
use the RequestFactory class introduced in Django 1.3 and call logIn in your test directly instead of using client.post.
inspect client.session after the post to check whether the user has been logged in.
Why one failing test can break another
When you edited the question, you asked
How this test can break another one?
The test_login_with_username was failing before it reached u.delete, so the user created in that test was not deleted. That caused test_user_register_with_unique_data_and_permission because the user test already existed.
If you use the django.test.TestCase class, the database will be reset in between each test, so this wouldn't be a problem.