Django TestCase using self.client.post() is sending a GET resquest - django

I'm creating a integration Test Class. The self.client.get is working fine, but self.client.post is sending GET and I'm receiving a [httpResponse("Method Not Allowed", 405)].
from django.test import TestCase
import json
class Test_Integration(TestCase):
def test_create_exist_product(self):
response = self.client.post('http://127.0.0.1:8201/v1/products/create', {"name": "product7", "latest_version": "0"}, follow=True, secure=False)
print(response)
self.assertEqual(response, "Product name already exists")
Function
def create_product(request):
logger.info("Entering function create_product..")
logger.info("REQUEST TYPE: "+str(request.method))
if request.method == "POST":
CODE HERE
return HttpResponse("Method Not Allowed", 405)
Log errors:
Found 4 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
INFO 2022-11-16 13:45:12,066 views 13612 19052 Entering function create_product..
INFO 2022-11-16 13:45:12,068 views 13612 19052 REQUEST TYPE: GET
<HttpResponse status_code=200, "405">
======================================================================
FAIL: test_create_exist_product (project.Tests.test_integration.Test_Integration)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\backend\project\Tests\test_integration.py", line 23, in test_create_exist_product
self.assertEqual(response, "Product name already exists")
AssertionError: <HttpResponse status_code=200, "405"> != 'Product name already exists'
----------------------------------------------------------------------
Ran 4 tests in 6.523s
FAILED (failures=1)
Destroying test database for alias 'default'...

Related

django test client returns 404, but works in the shell

This code works fine in the shell, but if you run it through python manage.py test it throws a 404 error, what could be the problem?
test_urls.py
from django.test import Client, TestCase
class StaticURLTests(TestCase):
def setUp(self):
self.guest_client = Client()
def test_homepage(self):
response = self.guest_client.get("/")
self.assertEqual(response.status_code, 200)
error:
❯ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_homepage (posts.tests.test_urls.StaticURLTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/finegorko/Development/Yandex.Practicum/hw03_forms/yatube/posts/tests/test_urls.py", line 10, in test_homepage
self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200
----------------------------------------------------------------------
Ran 1 test in 0.003s
FAILED (failures=1)
Destroying test database for alias 'default'...
The problem was that a test database was being created that did not have a group.
In views.py an object with the function get_object_or_404() was passed to the index context.
def index(request):
...
group = get_object_or_404(Group) # <--

Django Test assertTemplateUsed() failed: AssertionError: No templates used to render the response

I have an About page and written a test against it. The template renders well in the browser while the assertTemplatedUsed failed even the template name, url name and status code (returns 200) are all correct. Which part went wrong?
Thank you!
The error below:
System check identified no issues (0 silenced).
...F......
======================================================================
FAIL: test_aboutpage_template (pages.tests.AboutPageTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/code/pages/tests.py", line 54, in test_aboutpage_template
self.assertTemplateUsed(self.response, 'about.html')
File "/usr/local/lib/python3.8/site-packages/django/test/testcases.py", line 655, in assertTemplateUsed
self.fail(msg_prefix + "No templates used to render the response")
AssertionError: No templates used to render the response
----------------------------------------------------------------------
Ran 10 tests in 0.070s
FAILED (failures=1)
My test.py:
class AboutPageTests(SimpleTestCase):
def setUp(self):
url = reverse('about')
self.response = self.client.get(url)
def test_aboutpage_status_code(self):
self.assertEqual(self.response.status_code, 200)
def test_aboutpage_template(self):
self.assertTemplateUsed(self.response, 'about.html')

for loop in django unittest

I want to test register view in django project,
so I build some fake test cases(self.correct_samples)
after register successfully, it should redirect to home page which means the status code should be 302.
from django.test import TestCase
from django.urls.base import reverse
class RegisterTests(TestCase):
def setUp(self):
url = reverse('account:register')
self.response = self.client.get(url)
self.correct_samples = (
('testuser1#email.com', 'testuser', 'test112233', 'test112233'),
('fakeuser#email.com', 'fake123', 'fakeuser111', 'fakeuser111'),
('correct#email.com', 'Jack', 'myfavorite', 'myfavorite'),
('failemail', 'Jack', 'myfavorite', 'myfavorite'), # fail for purpose
)
def test_register_form(self):
for test_case in self.correct_samples:
email, username, password1, password2 = test_case
self.response = self.client.post(reverse('account:register'), data={
'email': email,
'username': username,
'password1': password1,
'password2': password2,
})
self.assertEqual(self.response.status_code, 302)
self.assertRedirects(
self.response, expected_url='/', status_code=302, target_status_code=200)
The fourth data in self.correct_samples which is ('failemail', 'Jack', 'myfavorite', 'myfavorite') should be a fail case.
but after python manage.py test. It passed.
(env) C:\Users\User\myblog>python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
C:\Users\User\myblog\env\lib\site-packages\whitenoise\base.py:115: UserWarning: No directory at: C:\Users\User\myblog\staticfiles\
warnings.warn(u"No directory at: {}".format(root))
.
----------------------------------------------------------------------
Ran 1 test in 0.195s
OK
Destroying test database for alias 'default'...
Here comes the tricky thing,
it failed after switching order from fourth to first.
from django.test import TestCase
from django.urls.base import reverse
class RegisterTests(TestCase):
def setUp(self):
...
self.correct_samples = (
('failemail', 'Jack', 'myfavorite', 'myfavorite'), # fail for purpose
('testuser1#email.com', 'testuser', 'test112233', 'test112233'),
('fakeuser#email.com', 'fake123', 'fakeuser111', 'fakeuser111'),
('correct#email.com', 'Jack', 'myfavorite', 'myfavorite'),
)
def test_register_form(self):
...
result:
(env) C:\Users\User\myblog>python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
C:\Users\User\myblog\env\lib\site-packages\whitenoise\base.py:115: UserWarning: No directory at: C:\Users\User\myblog\staticfiles\
warnings.warn(u"No directory at: {}".format(root))
F
======================================================================
FAIL: test_register_form (account.tests.RegisterTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\User\myblog\account\tests.py", line 34, in test_register_form
self.assertEqual(self.response.status_code, 302)
AssertionError: 200 != 302
----------------------------------------------------------------------
Ran 1 test in 0.026s
FAILED (failures=1)
Destroying test database for alias 'default'...
Why this happened?
I have searched for related keywords like unittest in forloop, multiple testcases in forloop.
but it seems no answers for it, or maybe search through other keywords?
or something I missed or misunderstood?
thanks for helping.
Problem has been solved!
According to this questions How do you generate dynamic (parameterized) unit tests in Python?
Solution: parameterized

"Unable to login with provided credentials" (on Testing)

I'm programming a test case for user register and login, I tested whit postman (chrome) and it works but the test case doesn't.
I'm using djangorestframework-jwt for authentication
Test:
class PublicUserTests(APITestCase):
def test_create_account(self):
url = "/api/user/create/"
data = {'email': 'clark#gmail.com', 'nombre': 'Clark', 'password': 'Clark'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data)
def test_login(self):
url = "/api/auth/token/"
response = self.client.post(url, {"email": "clark#gmail.com", "password": "Clark"}, format='json')
print(response.status_text)
print(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
Result:
Creating test database for alias 'default'...
.BAD REQUEST
b'{"non_field_errors":["Unable to login with provided credentials."]}'
F
======================================================================
FAIL: test_login (user.tests.PublicUserTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/rizotas/Proyects/django/src/rescue/user/tests.py", line 86, in test_login
self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
AssertionError: 400 != 200 : ReturnDict([('non_field_errors', ['Unable to login with provided credentials.'])])
----------------------------------------------------------------------
Ran 2 tests in 0.116s
FAILED (failures=1)
Destroying test database for alias 'default'...
Thanks so much for help me :)
Test methods in TestCase is not connected. So when test_login works he does not see user from test_create_account.
You need to create user before login in test_login.

No forms exist in unit test with django-webtest

I want to write a test that will test change the password in the application. I use the django-allauth. For testing, I use django-WebTest.
When I run my code, I get the message:
FAILED (errors=1)
Destroying test database for alias 'default'...
mark#mariusz-K73E:~/myapp$ python manage.py test users
Creating test database for alias 'default'...
.E
======================================================================
ERROR: test_password_change_use_template (myapp.users.tests.ChangePasswordTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/mark/myapp/users/tests.py", line 16, in test_password_change_use_template
password_change.form['oldpassword'] = "test123"
File "/home/mark/.virtualenvs/urlop/local/lib/python2.7/site-packages/webtest/response.py", line 56, in form
"You used response.form, but no forms exist")
TypeError: You used response.form, but no forms exist
My code:
from django_webtest import WebTest
from django_dynamic_fixture import G
from users.models import User
from django.core.urlresolvers import reverse
class ChangePasswordTest(WebTest):
def setUp(self):
self.user = G(User)
def test_password_change_code(self):
password_change = self.app.get(reverse('account_change_password'), user=self.user)
def test_password_change_use_template(self):
password_change = self.app.get(reverse('account_change_password'), user=self.user)
password_change.form['oldpassword'] = "test123"
password_change.form['password1'] = "test456"
password_change.form['password2'] = "test456"
password_change.form.submit()
self.assertRedirects(password_change, reverse('change_password'))
WebTest tests the rendered content. There is no form found in the HTML (maybe the form tag is incorrect or missing).
If it's working in your manual test. You can try to print the response to see what's different:
def test_password_change_use_template(self):
response = self.app.get(reverse('account_change_password'), user=self.user)
print response