Skip to content

Commit

Permalink
add a couple of captured queries tests
Browse files Browse the repository at this point in the history
  • Loading branch information
timgraham committed Oct 28, 2024
1 parent 17d8a5d commit d12ed39
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
Empty file added tests/queries_/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions tests/queries_/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.db import models


class Author(models.Model):
name = models.CharField(max_length=10)

def __str__(self):
return self.name


class Book(models.Model):
title = models.CharField(max_length=10)
author = models.ForeignKey(Author, models.CASCADE)

def __str__(self):
return self.title
26 changes: 26 additions & 0 deletions tests/queries_/test_mql.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from django.test import TestCase

from .models import Author, Book


class MQLTests(TestCase):
def test_all(self):
with self.assertNumQueries(1) as ctx:
list(Author.objects.all())
query = ctx.captured_queries[0]["sql"]
self.assertEqual(query, "db.queries__author.aggregate([{'$match': {'$expr': {}}}])")

def test_join(self):
with self.assertNumQueries(1) as ctx:
list(Book.objects.filter(author__name="Bob"))
query = ctx.captured_queries[0]["sql"]
self.assertEqual(
query,
"db.queries__book.aggregate(["
"{'$lookup': {'from': 'queries__author', "
"'let': {'parent__field__0': {'$convert': {'input': '$author_id', 'to': 'string'}}}, "
"'pipeline': [{'$match': {'$expr': {'$and': [{'$eq': ['$$parent__field__0', "
"{'$convert': {'input': '$_id', 'to': 'string'}}]}]}}}], 'as': 'queries__author'}}, "
"{'$unwind': '$queries__author'}, "
"{'$match': {'$expr': {'$eq': ['$queries__author.name', 'Bob']}}}])",
)

0 comments on commit d12ed39

Please sign in to comment.