Vai
Vai

Reputation: 353

Getting an assertion error while views testing using invalid data in django

I am testing my webapp by developing testcases using invalid data. Everything runs fine except for an assertion error that is bugging me a lot. I am trying to prevent a suer from registering if a same email id like his exists. In such a case, the same form will be rendered with the context as errors.(Check the code written below). But it keeps on showing an assertion error. Here is my code:

Here is my views.py:

def register(request):
    if request.method == 'POST':
        user_form = CustomUserCreationForm(data=request.POST)
        if user_form.is_valid():
            ob = CustomUserCreationForm.register(user_form)
            if ob.is_active is False and ob.is_staff is False:
                return render(request, 'todoapp/waiting.html')
            else:
                return render(request, 'todoapp/admin_success.html')
        else:
            return render(request, 'todoapp/register.html', {'errors': user_form.errors})
    return render(request, 'todoapp/register.html', {'form': CustomUserCreationForm()})

Here is my urls.py:

url(r'^register/', views.register, name='register'),

Here is my tests.py:

sent_data = {
            'first_name': 'john',
            'last_name': 'doe',
            'email': '[email protected]',
            'password': 'johndoe'
        }
        response = self.client.post(url, sent_data)
        self.assertEqual(response.status_code, 200)
        expected_data = {
            'email': 'User with this Email already exists.'
        }
        self.assertEqual(response.context['errors'], expected_data)

Here is the error:

self.assertEqual(response.context['errors'], expected_data)
AssertionError: {'email': [u'User with this Email already exists.']} != {u'errors': {u'email': u'User with this Email already exists.'}}

Upvotes: 1

Views: 1044

Answers (1)

Yugandhar Chaudhari
Yugandhar Chaudhari

Reputation: 3964

Assertion Error are because of left!=right here you want to compare the message as response you can check for this specific case

self.assertEqual(response.context['errors']['email'][0], expected_data['email'])

or

better you can modify your expected_data as errors comes in a list

expected_data = {
            'email': [u'User with this Email already exists.']
        }

self.assertEqual(response.context['errors'], expected_data)

Key is you see what response is actually getting returned and build your expected-data like that now onward.

Upvotes: 2

Related Questions