Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions django_mongodb_backend/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""Not a public API."""

from bson import SON, ObjectId


class MongoTestCaseMixin:
maxDiff = None

def assertAggregateQuery(self, query, expected_collection, expected_pipeline):
"""
Assert that the logged query is equal to:
db.{expected_collection}.aggregate({expected_pipeline})
"""
prefix, pipeline = query.split("(", 1)
_, collection, operator = prefix.split(".")
self.assertEqual(operator, "aggregate")
self.assertEqual(collection, expected_collection)
self.assertEqual(
eval(pipeline[:-1], {"SON": SON, "ObjectId": ObjectId}, {}), # noqa: S307
expected_pipeline,
)
19 changes: 14 additions & 5 deletions tests/lookup_/tests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from django.test import TestCase

from django_mongodb_backend.test import MongoTestCaseMixin

from .models import Book, Number


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


class RegexTests(TestCase):
class RegexTests(MongoTestCaseMixin, TestCase):
def test_mql(self):
# $regexMatch must not cast the input to string, otherwise MongoDB
# can't use the field's indexes.
with self.assertNumQueries(1) as ctx:
list(Book.objects.filter(title__regex="Moby Dick"))
query = ctx.captured_queries[0]["sql"]
self.assertEqual(
self.assertAggregateQuery(
query,
"db.lookup__book.aggregate(["
"{'$match': {'$expr': {'$regexMatch': {'input': '$title', "
"'regex': 'Moby Dick', 'options': ''}}}}])",
"lookup__book",
[
{
"$match": {
"$expr": {
"$regexMatch": {"input": "$title", "regex": "Moby Dick", "options": ""}
}
}
}
],
)
Loading
Loading