2

I wrote the following test for my Django application. The IntegrationDaily model has a constraint of max. 100 capacity. Therefore the entry will fail "on purpose". However, pytest.raises(Exception) seems to be the wrong approach to validate that. I also tried to import TransactionManagementError instead but that didn't solve it either.

import pytest

from tests.factories.spaces import IntegrationDailyFactory
from myapp.spaces.models import IntegrationDaily


def describe_element_capacity_validation():
    def with_is_failling():
        with pytest.raises(Exception) as exc:
            daily_element = IntegrationDailyFactory(capacity=300)

        assert IntegrationDaily.objects.count() == 0
Joey Coder
  • 3,199
  • 8
  • 28
  • 60

1 Answers1

1

Which Error is raised when it's more than 100? I assume it's IntegrityError.

from django.db import IntegrityError

with pytest.raises(IntegrityError) as e:
    daily_element = IntegrationDailyFactory(capacity=300)
dh762
  • 2,259
  • 4
  • 25
  • 44
  • 1
    The challenge here is that I am running into that error once I try that: `django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.` Currently reading about `@pytest.mark.django_db`, maybe that can solve it? – Joey Coder Aug 21 '20 at 11:48
  • 2
    this might be relevant: https://stackoverflow.com/a/23326971/1344855 – dh762 Aug 21 '20 at 11:54
  • 1
    Thank you everyone. Adding `@pytest.mark.django_db(transaction=True)` solved my problem. – Joey Coder Aug 21 '20 at 12:05