Skip to content

Commit

Permalink
Test num queries of latest_of_each()
Browse files Browse the repository at this point in the history
  • Loading branch information
ddabble committed Apr 14, 2024
1 parent 4d39103 commit ab64060
Showing 1 changed file with 22 additions and 15 deletions.
37 changes: 22 additions & 15 deletions simple_history/tests/tests/test_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import django
from django.contrib.auth import get_user_model
from django.db import IntegrityError
from django.db import IntegrityError, connection
from django.test import TestCase, override_settings, skipUnlessDBFeature

from simple_history.manager import SIMPLE_HISTORY_REVERSE_ATTR_NAME
Expand Down Expand Up @@ -151,33 +151,40 @@ def test_historical_query_set(self):
"""
Demonstrates how the HistoricalQuerySet works to provide as_of functionality.
"""
backend = connection.vendor
is_mysql = backend == "mysql"

document1 = RankedDocument.objects.create(rank=42)
document2 = RankedDocument.objects.create(rank=84)
document2.rank = 51
document2.save()
document1.delete()
t2 = datetime.now()

# look for historical records, get back a queryset
# Look for historical records, get back a queryset
with self.assertNumQueries(1):
queryset = RankedDocument.history.filter(history_date__lte=t2)
self.assertEqual(queryset.count(), 4)

# only want the most recend records (provided by HistoricalQuerySet)
self.assertEqual(queryset.latest_of_each().count(), 2)
# Only want the most recent records (provided by HistoricalQuerySet)
with self.assertNumQueries(2 if is_mysql else 1):
self.assertEqual(queryset.latest_of_each().count(), 2)

# want to see the instances as of that time?
self.assertEqual(queryset.latest_of_each().as_instances().count(), 1)
# Want to see the instances as of that time?
with self.assertNumQueries(2 if is_mysql else 1):
self.assertEqual(queryset.latest_of_each().as_instances().count(), 1)

# these new methods are idempotent
self.assertEqual(
queryset.latest_of_each()
.latest_of_each()
.as_instances()
.as_instances()
.count(),
1,
)
# These new methods are idempotent
# (One extra query per call to `latest_of_each()` when using MySQL)
with self.assertNumQueries(3 if is_mysql else 1):
self.assertEqual(
queryset.latest_of_each()
.latest_of_each()
.as_instances()
.as_instances()
.count(),
1,
)

# that was all the same as calling as_of!
self.assertEqual(
Expand Down

0 comments on commit ab64060

Please sign in to comment.