Skip to content

Commit

Permalink
Bail if the atomic update fails
Browse files Browse the repository at this point in the history
This should only happen due to race conditions or inconsistent data.
  • Loading branch information
WhyNotHugo committed Nov 16, 2023
1 parent e32e5fa commit 64c829e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
6 changes: 5 additions & 1 deletion django_afip/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1377,12 +1377,16 @@ def approximate_date(receipt: models.Receipt) -> bool:
return False

# Commit this atomically to avoid race conditions.
Receipt.objects.filter(
count = Receipt.objects.filter(
pk=receipt.id,
receipt_number__isnull=True,
).update(
issued_date=oldest_possible,
)
if count != 1:
raise exceptions.DjangoAfipException(
f"Expected to update one receipt, updated {count}."
)

# Mutate the input object to avoid inconsistency issues.
receipt.issued_date = oldest_possible
Expand Down
14 changes: 14 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,3 +559,17 @@ def test_approximate_date_two_days_ago_without_most_recent() -> None:

assert changed is False
assert receipt.issued_date == two_days_ago


@pytest.mark.django_db()
@freeze_time("2023-11-16 18:39:40")
def test_approximate_date_failure() -> None:
one_month_ago = date(2023, 10, 16)

receipt = factories.ReceiptWithApprovedValidation(issued_date=one_month_ago)

with pytest.raises(
exceptions.DjangoAfipException,
match="Expected to update one receipt, updated 0.",
):
receipt.approximate_date()

0 comments on commit 64c829e

Please sign in to comment.