Skip to content

Commit e180cbe

Browse files
WaVEVtimgraham
authored andcommitted
Add test for inserting a dollar prefixed string
This paves the way for fixing a problem with update in INTPYTHON-827.
1 parent 64c03ca commit e180cbe

File tree

4 files changed

+41
-4
lines changed

4 files changed

+41
-4
lines changed

django_mongodb_backend/test.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
class MongoTestCaseMixin:
77
maxDiff = None
8+
query_types = {"SON": SON, "ObjectId": ObjectId, "Decimal128": Decimal128}
89

910
def assertAggregateQuery(self, query, expected_collection, expected_pipeline):
1011
"""
@@ -15,7 +16,15 @@ def assertAggregateQuery(self, query, expected_collection, expected_pipeline):
1516
_, collection, operator = prefix.split(".")
1617
self.assertEqual(operator, "aggregate")
1718
self.assertEqual(collection, expected_collection)
18-
self.assertEqual(
19-
eval(pipeline[:-1], {"SON": SON, "ObjectId": ObjectId, "Decimal128": Decimal128}, {}), # noqa: S307
20-
expected_pipeline,
21-
)
19+
self.assertEqual(eval(pipeline[:-1], self.query_types, {}), expected_pipeline) # noqa: S307
20+
21+
def assertInsertQuery(self, query, expected_collection, expected_documents):
22+
"""
23+
Assert that the logged query is equal to:
24+
db.{expected_collection}.insert_many({expected_documents})
25+
"""
26+
prefix, pipeline = query.split("(", 1)
27+
_, collection, operator = prefix.split(".")
28+
self.assertEqual(operator, "insert_many")
29+
self.assertEqual(collection, expected_collection)
30+
self.assertEqual(eval(pipeline[:-1], self.query_types), expected_documents) # noqa: S307

tests/basic_/__init__.py

Whitespace-only changes.

tests/basic_/models.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from django.db import models
2+
3+
4+
class Author(models.Model):
5+
name = models.CharField(max_length=50)
6+
7+
def __str__(self):
8+
return self.name

tests/basic_/test_escaping.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
"""Literals that MongoDB intreprets as expressions are escaped."""
2+
3+
from django.test import TestCase
4+
5+
from django_mongodb_backend.test import MongoTestCaseMixin
6+
7+
from .models import Author
8+
9+
10+
class ModelCreationTests(MongoTestCaseMixin, TestCase):
11+
def test_dollar_prefixed_string(self):
12+
# No escaping is needed because MongoDB's insert doesn't treat
13+
# dollar-prefixed strings as expressions.
14+
with self.assertNumQueries(1) as ctx:
15+
obj = Author.objects.create(name="$foobar")
16+
obj.refresh_from_db()
17+
self.assertEqual(obj.name, "$foobar")
18+
self.assertInsertQuery(
19+
ctx.captured_queries[0]["sql"], "basic__author", [{"name": "$foobar"}]
20+
)

0 commit comments

Comments
 (0)