Skip to content

Commit d12ed39

Browse files
committed
add a couple of captured queries tests
1 parent 17d8a5d commit d12ed39

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

tests/queries_/__init__.py

Whitespace-only changes.

tests/queries_/models.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from django.db import models
2+
3+
4+
class Author(models.Model):
5+
name = models.CharField(max_length=10)
6+
7+
def __str__(self):
8+
return self.name
9+
10+
11+
class Book(models.Model):
12+
title = models.CharField(max_length=10)
13+
author = models.ForeignKey(Author, models.CASCADE)
14+
15+
def __str__(self):
16+
return self.title

tests/queries_/test_mql.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from django.test import TestCase
2+
3+
from .models import Author, Book
4+
5+
6+
class MQLTests(TestCase):
7+
def test_all(self):
8+
with self.assertNumQueries(1) as ctx:
9+
list(Author.objects.all())
10+
query = ctx.captured_queries[0]["sql"]
11+
self.assertEqual(query, "db.queries__author.aggregate([{'$match': {'$expr': {}}}])")
12+
13+
def test_join(self):
14+
with self.assertNumQueries(1) as ctx:
15+
list(Book.objects.filter(author__name="Bob"))
16+
query = ctx.captured_queries[0]["sql"]
17+
self.assertEqual(
18+
query,
19+
"db.queries__book.aggregate(["
20+
"{'$lookup': {'from': 'queries__author', "
21+
"'let': {'parent__field__0': {'$convert': {'input': '$author_id', 'to': 'string'}}}, "
22+
"'pipeline': [{'$match': {'$expr': {'$and': [{'$eq': ['$$parent__field__0', "
23+
"{'$convert': {'input': '$_id', 'to': 'string'}}]}]}}}], 'as': 'queries__author'}}, "
24+
"{'$unwind': '$queries__author'}, "
25+
"{'$match': {'$expr': {'$eq': ['$queries__author.name', 'Bob']}}}])",
26+
)

0 commit comments

Comments
 (0)