W
W
wawa2018-07-08 13:52:47
Django
wawa, 2018-07-08 13:52:47

How to test code with regular database level errors?

When I register in a view, the following happens:

if form.is_valid():
        try:
            user = User.objects.create_user(
                email=form.cleaned_data['email'],
                password=form.cleaned_data['password1']
            )
        except IntegrityError:
            user = User.objects.get(email=form.cleaned_data['email'])
            ...

Everything works as it should. But can't test this code in django.test.TestCase:
ERROR: test_registration_when_existing_inactive_email (accounts.test_views.SignupTest)
---------------------------------------- ------------------------------
Traceback (most recent call last):
...
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: ERROR: Duplicate key value violates unique constraint "accounts_user_email_key"
DETAIL: Key "(email)=([email protected])" already exists.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
...
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: ERROR: Duplicate key value violates unique constraint 'accounts_user_email_key'
DETAIL: Key '(email)=([email protected])' already exists.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
...
django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
-------------------------------------------------- --------------------
Ran 16 tests in 1.498s
FAILED (errors=1)
Destroying test database for alias 'default'...

Obviously IntegrityError interferes with the test, but this error is normal behavior. How to test such code?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question