setUpClass() is being called multiple times in DRF - django

Perhaps I am missing the logic but I want to add two unique records to a model then run my tests on an API. But my API complains .get() has returned 2 records, raising the error. I notice the error happens on my .post() check, while the get methods work well. Is it a bug?
only enough if I change self.client.post with .get(), it doesn't complain.
I have tried setUpTestData() since my database supports Transactions to no avail. Essentially, I want to try the get method and the post methods. All the get operations pass but on the post test, it fails.
class ResetPwdTest(APITestCase):
""" Test module for resetting forgotten password """
#classmethod
def setUpClass(cls):
super().setUpClass()
cls.valid_payload = '1234567890ABCDEF'
cls.expired_payload = '1234567ACDES'
cls.invalid_payload = 'invalid0000'
user_info = {'first_name': 'John', 'email': 'kmsium#gmail.com','password' : 'kigali11', 'status': 1}
user = User.objects.create_user(**user_info)
PasswordReset.objects.all().delete() # delete any possible we have but having no effect so far
# create valid password token
password2 = PasswordReset(profile_id=user.id, unique_code=cls.valid_payload)
password2.save()
# create an expired passwod token
password = PasswordReset(profile_id=user.id, unique_code=cls.expired_payload)
password.save()
password.createdon = '2018-01-12 21:11:38.997207'
password.save()
def test_valid_token(self):
"""
GET Ensure a valid forgotten password reset token returns 200
WORKING
"""
response = self.client.get(reverse('new-pwd', kwargs= {'token' : self.valid_payload}))
self.assertEqual(response.status_code, 200)
def test_expired_token(self):
"""
GET Ensure an expired token to reset a forgotten password returns 400
WORKING
"""
response = self.client.get(reverse('new-pwd', kwargs= {'token' : self.expired_payload}))
self.assertEqual(response.status_code, 400)
def test_invalid_token(self):
"""
GET Ensure an invali token to reset a forgotten password returns 400
WORKING
"""
response = self.client.get(reverse('new-pwd', kwargs= {'token' : self.invalid_payload}))
self.assertEqual(response.status_code, 400)
def test_valid_token_change_pass(self):
"""
POST Ensure a valid forgotten password with accepted passwords pass reset token returns 200
FAILING BECAUSE TOKEN is not unique
"""
passwords = {'pwd': 'letmein11', 'pwd_confirm': 'letmein11'}
response = self.client.post(reverse('new-pwd', kwargs= {'token' : self.valid_payload}), passwords, format='json')
self.assertEqual(response.status_code, 200)
the View:
class ResetPwd(APIView):
permission_classes = []
def get(self,request,token,format=None):
status = 400
reply = {}
check_token = PasswordReset.objects.values('createdon','profile_id',).get(unique_code=token)
# exists but is it valid or not? It cant be
createdon = check_token["createdon"]
if createdon > timezone.now() - timedelta(hours=USER_VALUES['PWD_RESET_LIFESPAN']):
status = 200
reply['detail'] = True
else:
reply['detail'] = _('errorPwdResetLinkExpired')
return JsonResponse(reply,status=status)
def post(self,request,token,format=None):
'''
#input pwd: password
#input pwd_confirm : confirmation password
'''
status = 400
reply = {}
k = PasswordReset.objects.filter(unique_code= token).count()
print('total in db ', k) # shows 1
check_token = PasswordReset.objects.values('createdon','profile_id',).get(unique_code=token)
# error: returning 2!
#exists but is it valid or not? It cant be
createdon = check_token['createdon']
if createdon > timezone.now() - timedelta(hours=USER_VALUES['PWD_RESET_LIFESPAN']):
status = 200
else:
reply['detail'] = _('errorPwdResetLinkExpired')
'''
except:
reply['detail'] = _('errorBadPwdResetLink')
'''
return JsonResponse(reply,status=status)
I expect all the tests to pass.

Related

MultiValueDictKeyError in Django REST APIView POST request

I am trying to write a POST request for a game API and am passing some data from the GET request and some through this POST request. However, I keep getting the following error:
MultiValueDictKeyError 'gameround'
What am I doing wrong here?
def post(self, request, *args, **kwargs):
if not isinstance(request.user, CustomUser):
current_user_id = 1
else:
current_user_id = request.user.pk
gameround = request.GET['gameround']
random_resource = request.GET['resource']
created = datetime.now()
score = 0
origin = ''
name = request.POST['name']
language = request.POST['language']
user_input_tag = Tag.objects.create(name=name, language=language)
tag_serializer = TagSerializer(user_input_tag)
if Tagging.objects.all().filter(tag=user_input_tag).exists():
# if tagging like this exists, save tagging anyway and leave tag unchanged
score += 5
user_input_tagging = Tagging.objects.create(user_id=current_user_id,
gameround=gameround,
resource=random_resource,
tag=user_input_tag,
created=created,
score=score,
origin=origin)
tagging_serializer = TaggingSerializer(user_input_tagging)
return Response({'tag and ': tag_serializer.data}, {'tagging': tagging_serializer.data})
elif not Tagging.objects.all().filter(tag=user_input_tag).exists():
# save tagging otherwise and del tag?
user_input_tagging = Tagging.objects.create(user_id=current_user_id,
gameround=gameround,
resource=random_resource,
tag=user_input_tag,
created=created,
score=score,
origin=origin)
user_input_tagging.save()
tagging_serializer = TaggingSerializer(user_input_tagging)
return Response({'tagging only': tagging_serializer.data})
You don't have key gameround in your GET. You can get gameround data as
gameround = request.GET.get('gameround')
If default value is not given then it defaults to None.
Or you can set default value as
gameround = request.GET.get('gameround', '')

Django REST testing - how to specify pk argument referring to the model instance created in setUp function

I have a model "Article" and I want to test if authorized user can GET an individual article.
The testing class is:
class TestPost(APITestCase):
def setUp(self):
self.factory = APIRequestFactory()
self.user = User.objects.create_user(
username='Name', email='test#company.com', password='secret')
self.article = Article.objects.create(
author = 'Author', title = 'Article title', body = 'Body content ...')
def test_detail_user(self):
request = self.factory.get(reverse('article_id', kwargs={'pk': 1}))
request.user = self.user
response = ArticleDetail.as_view()(request, pk=1)
self.assertEqual(response.status_code, 200,
f'Expected Response Code 200 - OK, received {response.status_code} instead.')
The URL pattern is:
path('<int:pk>/', ArticleDetail.as_view(), name = 'article_id'),
And when running tests I get the following error:
f'Expected Response Code 200 - OK, received {response.status_code} instead.')
AssertionError: 404 != 200 : Expected Response Code 200 - OK, received 404 instead.
I suppose the problem is in the specified 'pk', but I cannot figure out how to specify pk without stating an exact figure of 1. How can I refer to the article created in setUp function instead?
I may be misunderstanding, but you should be able to reference it by simply doing something like:
def test_detail_user(self):
article_id = self.article.pk
...
# the rest of your code here using article_id as the id of
# the article you are retrieving

Raising validation error in django form for the api

I am new to django and python development and am naive in my understanding of how to handle exceptions.
I am registering a user through an api call by calling the method register, and would like to push the success status or the error messages while registration.
def register(self,request, **kwargs):
try:
data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
email = data['email']
password = data['password']
firstname = data['firstname']
lastname = data['lastname']
newdata = {'email' : email , 'password1': password , 'password2':password, 'firstname':'firstname' , 'lastname':lastname }
registrationform = UserEmailRegistrationForm(newdata)
print registrationform.errors.as_text
print registrationform.cleaned_data
cleaned_data = registrationform.cleaned_data
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(cleaned_data['username'],cleaned_data['email'],cleaned_data['password1'], site)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request,**cleaned_data)
registerUser = collections.OrderedDict()
registerUser['return']='0'
registerUser['code']='0'
registerUser['message']='registered user'
return HttpResponse(registerUser, content_type="application/json")
except Exception, e:
logging.exception(e)
registerUser = collections.OrderedDict()
registerUser['return']='0'
registerUser['code']='0'
registerUser['message']='registered user'
return HttpResponse(registerUser, content_type="application/json")
When I execute this, for example with an already registered email, I get the following in registrationform.errors.as_text
bound method ErrorDict.as_text of {'email': [u'A user with that email already exists.']}>
What would be the right way to code exceptions so that I can pass the success message if the form was validated and user was registered, and the error message if there was a validation error?
Any help is much appreciated!
You might want to have a look in the form's is_valid() method: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.is_valid
For example
if registrationform.is_valid():
//do your stuff
....
register['error'] = False
else:
//return the errors
registerUser['message'] = _('Oops! Please fix the following errors')
register['error'] = True
register['errors'] = registrationform.errors
....

Problem with pymongo and django unique value

I am writing django app that as a beckend is using mongodb. I am curently writing register part. Here is how I connecto to database in settings.py
if socket.gethostname() == "Production server":
CON = Connection()
DB = CON.fish
else:
CON = Connection()
DB = CON.test
DB.user.ensure_index([("username", ASCENDING),("email",ASCENDING)],unique = True)#,drop_dups=True
Here is mye register view:
def register(request):
"""
handle user registration
code variable is for testing purposes
"""
if request.method== 'GET':
form = RegisterForm(auto_id=False)
code = 1
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
elif request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
password = form.cleaned_data['password']
password_confirmation = form.cleaned_data['password_confirmation']
if password == password_confirmation:
login = form.cleaned_data['login']
email = form.cleaned_data['email']
newsletter = form.cleaned_data['newsletter']
key = register_user(login,email,password,newsletter)
if key:
#send email
send_mail("Dziękujemy za rejestrację"," Klucz aktywacyjny to " + key,settings.EMAIL_HOST_USER,[email])
request.session['email'] = email
return redirect(register_success)
else:
code = 4
error = "Login/email taken"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 3
error = "invalid password"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 2
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
Here is my function I use to register user:
def register_user(login,email,password,newsletter):
"""
This function will return activation key for this user if user was added successfully or none otherwise
"""
key = generate_activation_key()
user = {
"username":login,
"email":email,
"password":crypt_password(password),
"date_join": datetime.now(),
"key": key
}
if newsletter:
user['newsletter'] = True
try:
settings.DB.user.insert(user,safe = True)
except DuplicateKeyError, error:
logging.debug("error raise during saving user")
return None
except OperationFailure, error:
logging.critical("Cannot save to database")
logging.critical(error)
else:
#we have no errors users is registred
return key
And when I test it in the browser it seems to be working. But I write test for it and it isn't working anymore. Here is code for test:
def test_valid_credentials(self):
#now try to register valid user
data = {'login':'test','password':'zaq12wsx','password_confirmation':'zaq12wsx','terms':True,'newsletter':True,'email':'test#test.com'}
response = self.c.post(reverse('register'),data)
#our user should be registred
self.assertEquals(302, response.status_code,'We dont have benn redirected')
self.assertEqual(len(mail.outbox), 1,'No activation email was sent')
#clen email box
mail.outbox = []
#now try to add another user with the same data
response = self.c.post(reverse('register'),data)
#template should be rendered with error message about used login and email
self.assertEquals(200, response.status_code)#this fails
And here is error that i get.
self.assertEquals(200, response.status_code)
AssertionError: 200 != 302
So user was registred with the same username and email which shoudn't happen. Any sugestions? Thanks in advance
Why don't you use https://github.com/django-mongodb-engine/mongodb-engine it works almost perfect with Django ORM. Works like a charm for me.

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.