Skip to content

Commit 556dfb2

Browse files
committed
Add MongoTestCaseMixin.assertAggregateQuery()
1 parent d7f8fd2 commit 556dfb2

File tree

3 files changed

+713
-475
lines changed

3 files changed

+713
-475
lines changed

django_mongodb_backend/test.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
"""Not a public API at this time."""
2+
3+
4+
class MongoTestCaseMixin:
5+
def assertAggregateQuery(self, query, expected_collection, expected_pipeline):
6+
"""
7+
Assert that the logged query is equal to:
8+
db.{expected_collection}.aggregate({expected_pipeline})
9+
"""
10+
prefix, pipeline = query.split("(", 1)
11+
_, collection, operator = prefix.split(".")
12+
self.assertEqual(operator, "aggregate")
13+
self.assertEqual(collection, expected_collection)
14+
self.assertEqual(eval(pipeline[:-1]), expected_pipeline) # noqa: S307

tests/lookup_/tests.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from django.test import TestCase
22

3+
from django_mongodb_backend.test import MongoTestCaseMixin
4+
35
from .models import Book, Number
46

57

@@ -17,16 +19,23 @@ def test_lte(self):
1719
self.assertQuerySetEqual(Number.objects.filter(num__lte=3), self.objs[:4])
1820

1921

20-
class RegexTests(TestCase):
22+
class RegexTests(MongoTestCaseMixin, TestCase):
2123
def test_mql(self):
2224
# $regexMatch must not cast the input to string, otherwise MongoDB
2325
# can't use the field's indexes.
2426
with self.assertNumQueries(1) as ctx:
2527
list(Book.objects.filter(title__regex="Moby Dick"))
2628
query = ctx.captured_queries[0]["sql"]
27-
self.assertEqual(
29+
self.assertAggregateQuery(
2830
query,
29-
"db.lookup__book.aggregate(["
30-
"{'$match': {'$expr': {'$regexMatch': {'input': '$title', "
31-
"'regex': 'Moby Dick', 'options': ''}}}}])",
31+
"lookup__book",
32+
[
33+
{
34+
"$match": {
35+
"$expr": {
36+
"$regexMatch": {"input": "$title", "regex": "Moby Dick", "options": ""}
37+
}
38+
}
39+
}
40+
],
3241
)

0 commit comments

Comments
 (0)