Wednesday, September 25, 2024

Re: testing signal with django allauth

Hey, I finally managed to test the signal!! As it has been a complicated and long process, I wrote an article about how to perform actions after authentication and how to test it.

On Monday 23 September 2024 at 15:18:52 UTC+1 Gabriel Soler wrote:
Yup, that's the problem; I am trying to test something that comes from a third-party app called Allah. And I cannot get it right :/

On Monday 23 September 2024 at 13:44:21 UTC+1 RANGA BHARATH JINKA wrote:
In Django, when using `TestCase` for testing views, CSRF tokens are indeed not necessary since the test client does not enforce CSRF protection. However, if you're testing forms directly (like a `ModelForm`), you generally don't need to provide a CSRF token either, as the form itself does not directly interact with the CSRF protection mechanism when instantiated in tests.

When you pass a dictionary to a `ModelForm`, you're typically dealing with form validation. If your form is instantiated with data that's invalid, it won't affect CSRF tokens, as they come into play mainly with POST requests in views.

So, you can test your form validation without worrying about CSRF tokens. Please make sure that the data you pass in simulates the conditions you want to test!

On Mon, Sep 23, 2024 at 5:38 PM Gabriel Soler <gso...@gmail.com> wrote:
Hi Ranga, thanks for the response,

My test log is quite simple; it is not true the form is valid, and there is a little change in the session to mark it when my function did not change. 
As I am using TestCase I understand that the CSRF tokens are unnecessary. Would passing the dictionary to the modelForm need a CSRF token too?


"""
Traceback (most recent call last):
  File "/Users/gsole/Documents/Web-Work/between/between_app/test_login_integration.py", line 78, in test_login_after_test
    self.assertEqual(self.client.session['linked'],"true")
AssertionError: 'false' != 'true'
- false
+ true


======================================================================
FAIL: test_login_form_is_valid (between_app.test_login_integration.ProfileLinkUserAutenticate.test_login_form_is_valid)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/gsole/Documents/Web-Work/between/between_app/test_login_integration.py", line 67, in test_login_form_is_valid
    self.assertTrue(login_valid.is_valid())
AssertionError: False is not true

----------------------------------------------------------------------
"""
On Monday 23 September 2024 at 12:36:37 UTC+1 RANGA BHARATH JINKA wrote:
what's the error you are getting in the logs ?

In Django, while writing tests for forms that require CSRF token validation (for instance, in Test-Driven Development or TDD), you can bypass the CSRF validation or simulate the behavior of submitting a valid CSRF token.

Here's how you can handle CSRF tokens in your Django tests:

### 1. **Bypassing CSRF Validation in Tests**
Django's test client automatically ignores CSRF checks when running tests. This means that when you use Django's `Client` in your tests, you don't need to worry about CSRF tokens. You can directly submit forms without providing a CSRF token.

#### Example:
```python
from django.test import TestCase
from django.urls import reverse

class MyFormTest(TestCase):
    def test_form_submission(self):
        url = reverse('my_form_url')
        form_data = {
            'field1': 'value1',
            'field2': 'value2',
        }
        response = self.client.post(url, form_data)
        self.assertEqual(response.status_code, 200)
```
In this example, Django automatically bypasses the CSRF check when the form is submitted via the `self.client.post()`.

### 2. **Simulating CSRF Token (If Required for Specific Use Case)**
If, for some reason, you want to simulate the behavior of CSRF protection in tests, you can manually add the CSRF token to your form data. To do this, retrieve the CSRF token from the response context and include it in the form submission.

#### Example:
```python
from django.test import TestCase
from django.urls import reverse

class MyFormTest(TestCase):
    def test_form_submission_with_csrf(self):
        # Retrieve the form page to get the CSRF token
        url = reverse('my_form_url')
        response = self.client.get(url)
        csrf_token = response.cookies['csrftoken'].value

        form_data = {
            'csrfmiddlewaretoken': csrf_token,
            'field1': 'value1',
            'field2': 'value2',
        }
        response = self.client.post(url, form_data)
        self.assertEqual(response.status_code, 200)
```

### 3. **Custom CSRF Token Checking (Optional)**
If you are writing custom views or custom middleware that depends on CSRF tokens, you might want to ensure that CSRF tokens are handled in tests. This typically isn't necessary with Django's built-in forms and views, but it could be useful if you have custom security logic.

### Conclusion
For most scenarios in Django TDD, you don't need to pass the CSRF token in tests since Django's test client ignores CSRF by default. However, if you do need to simulate it, you can explicitly add the CSRF token from the response context to your form submission.


On Mon, Sep 23, 2024 at 5:02 PM RANGA BHARATH JINKA <bharath...@gmail.com> wrote:
Hi,

I think you have to pass csrf token while submitting the form in django. Try passing csrf token.

On Mon, Sep 23, 2024 at 4:34 PM Gabriel Soler <gso...@gmail.com> wrote:
Sorry, I did not add the code before. This is how I have my tests set up at the moment. I cannot pass the 'form is valid' step. 

from django.test import TestCase,Client
from django.urls import reverse, reverse_lazy
from django.contrib.auth import get_user_model
from .forms import StyleForm
from allauth.account.forms import LoginForm
from django.test.utils import override_settings
from allauth.account import app_settings



class ProfileLinkUserAutenticate(TestCase):
"""to test if the open profile test saves after login and signup """

fixtures = ['between_app/fixtures/PersonalStyleGroup.yaml',
'between_app/fixtures/PersonalStyleSection.yaml'
]
def setup(self):
self.client = Client() #to explore templates in request
@classmethod
def setUpTestData(cls):
cls.login_data = {'password':'test123%%HH','remember':'t',
'username':'usertest'}
cls.user = get_user_model().objects.create_user(
username = 'usertest',
email = 'te...@test.com',
password = 'test123%%HH',
)
cls.data = {
'follower_1':90,
'propositive_1':2,
'challenger_1':6,
'acceptant_1':10,
'intensive_1':20,
'extensive_1':6,
'divider_1':3,
'containment_1':30,
'becoming_1':1,
'development_1':60,
'individuation_1':10,
'belonging_1':3,

}

def test_client_login(self):
self.client.login(
username = 'usertest',
email = 'te...@test.com',
password = 'test123',
)
self.assertTrue(self.user.is_authenticated)
self.client.logout()
def test_form_valid(self):
form_invalid = StyleForm(data={"name": "Computer", "price": 400.1234})
self.assertFalse(form_invalid.is_valid())
form_valid = StyleForm(data=self.data)
self.assertTrue(form_valid.is_valid())
def test_post_form(self):
response = self.client.post('/profile_test/',self.data, follow=True)
self.assertEqual(self.client.session['linked'],"false")
self.assertContains(response,"Compassionate")

def test_login_form_is_valid(self):
login_valid = LoginForm(data=self.login_data)
self.assertTrue(login_valid.is_valid())
def test_login_after_test(self):
self.client.logout()
response = self.client.post('/profile_test/',self.data, follow=True)
self.assertEqual(self.client.session['linked'],"false")
response = self.client.post(reverse('account_login'),data=self.login_data)
#self.assertRedirects(response=response,expected_url='/')
#self.client.login(username='usertest',password='test123')
response = self.client.get('')
#self.assertContains(response,"Welcome back")
self.assertEqual(self.client.session['linked'],"true")
#self.assertContains(response,"Welcome back")


On Saturday 21 September 2024 at 21:08:39 UTC+1 Gabriel Soler wrote:
Hi all, 

Thanks for reading. I am at a stage where I am needing to do my testing, and its is hard!
I managed to add a function after sign up and log in, using the signals of allauth. As I am trying to add my tests as I work, I have added a little change to the Session, to mark if my functions have don what they should, and I also would like to test if actually is doing the thing.
Now, when I try with the unit tests to send a dictionary with the login I am not being able to do a form that is valid for allauth. Can somebody help we figuring out how to test this? Or some wisdom about testing? (My function is working, but I am learning about testing, and test driven development, and I came to it because I have been fearing to do changes and then create unknown bugs, so it is time!)

Gabriel

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/44e9f138-a9b0-417e-8665-f9003521d6c4n%40googlegroups.com.


--
Thanks and Regards

J. Ranga Bharath
cell: 9110334114


--
Thanks and Regards

J. Ranga Bharath
cell: 9110334114

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.


--
Thanks and Regards

J. Ranga Bharath
cell: 9110334114

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1eeb8f17-48dc-4e26-a9a9-0142156f8dedn%40googlegroups.com.

No comments:

Post a Comment