Skip to content

Commit dc134f6

Browse files
committed
Add MongoTestCaseMixin.assertAggregateQuery()
1 parent 5fbe0f6 commit dc134f6

File tree

3 files changed

+721
-475
lines changed

3 files changed

+721
-475
lines changed

django_mongodb_backend/test.py

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

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)