Debian Codegraph @

tests/queries/test_q.py

raw
1 from datetime import datetime
2
3 from django.core.exceptions import FieldError
4 from django.db import connection
5 from django.db.models import (
6 BooleanField,
7 Exists,
8 ExpressionWrapper,
9 F,
10 OuterRef,
11 Q,
12 Value,
13 )
14 from django.db.models.expressions import NegatedExpression, RawSQL
15 from django.db.models.functions import ExtractDay, Lower, TruncDate
16 from django.db.models.lookups import (
17 Exact,
18 IntegerFieldExact,
19 IntegerLessThanOrEqual,
20 IsNull,
21 )
22 from django.db.models.sql.where import NothingNode
23 from django.test import SimpleTestCase, TestCase
24
25 from .models import Tag
26
27
28 class QTests(SimpleTestCase):
29 def test_combine_and_empty(self):
30 q = Q(x=1)
31 self.assertEqual(q & Q(), q)
32 self.assertEqual(Q() & q, q)
33
34 q = Q(x__in={}.keys())
35 self.assertEqual(q & Q(), q)
36 self.assertEqual(Q() & q, q)
37
38 def test_combine_and_both_empty(self):
39 self.assertEqual(Q() & Q(), Q())
40
41 def test_combine_or_empty(self):
42 q = Q(x=1)
43 self.assertEqual(q | Q(), q)
44 self.assertEqual(Q() | q, q)
45
46 q = Q(x__in={}.keys())
47 self.assertEqual(q | Q(), q)
48 self.assertEqual(Q() | q, q)
49
50 def test_combine_xor_empty(self):
51 q = Q(x=1)
52 self.assertEqual(q ^ Q(), q)
53 self.assertEqual(Q() ^ q, q)
54
55 q = Q(x__in={}.keys())
56 self.assertEqual(q ^ Q(), q)
57 self.assertEqual(Q() ^ q, q)
58
59 def test_combine_empty_copy(self):
60 base_q = Q(x=1)
61 tests = [
62 base_q | Q(),
63 Q() | base_q,
64 base_q & Q(),
65 Q() & base_q,
66 base_q ^ Q(),
67 Q() ^ base_q,
68 ]
69 for i, q in enumerate(tests):
70 with self.subTest(i=i):
71 self.assertEqual(q, base_q)
72 self.assertIsNot(q, base_q)
73
74 def test_combine_or_both_empty(self):
75 self.assertEqual(Q() | Q(), Q())
76
77 def test_combine_xor_both_empty(self):
78 self.assertEqual(Q() ^ Q(), Q())
79
80 def test_combine_not_q_object(self):
81 obj = object()
82 q = Q(x=1)
83 with self.assertRaisesMessage(TypeError, str(obj)):
84 q | obj
85 with self.assertRaisesMessage(TypeError, str(obj)):
86 q & obj
87 with self.assertRaisesMessage(TypeError, str(obj)):
88 q ^ obj
89
90 def test_combine_negated_boolean_expression(self):
91 tagged = Tag.objects.filter(category=OuterRef("pk"))
92 tests = [
93 Q() & ~Exists(tagged),
94 Q() | ~Exists(tagged),
95 Q() ^ ~Exists(tagged),
96 ]
97 for q in tests:
98 with self.subTest(q=q):
99 self.assertIsInstance(q, NegatedExpression)
100
101 def test_deconstruct(self):
102 q = Q(price__gt=F("discounted_price"))
103 path, args, kwargs = q.deconstruct()
104 self.assertEqual(path, "django.db.models.Q")
105 self.assertEqual(args, (("price__gt", F("discounted_price")),))
106 self.assertEqual(kwargs, {})
107
108 def test_deconstruct_negated(self):
109 q = ~Q(price__gt=F("discounted_price"))
110 path, args, kwargs = q.deconstruct()
111 self.assertEqual(args, (("price__gt", F("discounted_price")),))
112 self.assertEqual(kwargs, {"_negated": True})
113
114 def test_deconstruct_or(self):
115 q1 = Q(price__gt=F("discounted_price"))
116 q2 = Q(price=F("discounted_price"))
117 q = q1 | q2
118 path, args, kwargs = q.deconstruct()
119 self.assertEqual(
120 args,
121 (
122 ("price__gt", F("discounted_price")),
123 ("price", F("discounted_price")),
124 ),
125 )
126 self.assertEqual(kwargs, {"_connector": Q.OR})
127
128 def test_deconstruct_xor(self):
129 q1 = Q(price__gt=F("discounted_price"))
130 q2 = Q(price=F("discounted_price"))
131 q = q1 ^ q2
132 path, args, kwargs = q.deconstruct()
133 self.assertEqual(
134 args,
135 (
136 ("price__gt", F("discounted_price")),
137 ("price", F("discounted_price")),
138 ),
139 )
140 self.assertEqual(kwargs, {"_connector": Q.XOR})
141
142 def test_deconstruct_and(self):
143 q1 = Q(price__gt=F("discounted_price"))
144 q2 = Q(price=F("discounted_price"))
145 q = q1 & q2
146 path, args, kwargs = q.deconstruct()
147 self.assertEqual(
148 args,
149 (
150 ("price__gt", F("discounted_price")),
151 ("price", F("discounted_price")),
152 ),
153 )
154 self.assertEqual(kwargs, {})
155
156 def test_deconstruct_multiple_kwargs(self):
157 q = Q(price__gt=F("discounted_price"), price=F("discounted_price"))
158 path, args, kwargs = q.deconstruct()
159 self.assertEqual(
160 args,
161 (
162 ("price", F("discounted_price")),
163 ("price__gt", F("discounted_price")),
164 ),
165 )
166 self.assertEqual(kwargs, {})
167
168 def test_deconstruct_nested(self):
169 q = Q(Q(price__gt=F("discounted_price")))
170 path, args, kwargs = q.deconstruct()
171 self.assertEqual(args, (Q(price__gt=F("discounted_price")),))
172 self.assertEqual(kwargs, {})
173
174 def test_deconstruct_boolean_expression(self):
175 expr = RawSQL("1 = 1", BooleanField())
176 q = Q(expr)
177 _, args, kwargs = q.deconstruct()
178 self.assertEqual(args, (expr,))
179 self.assertEqual(kwargs, {})
180
181 def test_reconstruct(self):
182 q = Q(price__gt=F("discounted_price"))
183 path, args, kwargs = q.deconstruct()
184 self.assertEqual(Q(*args, **kwargs), q)
185
186 def test_reconstruct_negated(self):
187 q = ~Q(price__gt=F("discounted_price"))
188 path, args, kwargs = q.deconstruct()
189 self.assertEqual(Q(*args, **kwargs), q)
190
191 def test_reconstruct_or(self):
192 q1 = Q(price__gt=F("discounted_price"))
193 q2 = Q(price=F("discounted_price"))
194 q = q1 | q2
195 path, args, kwargs = q.deconstruct()
196 self.assertEqual(Q(*args, **kwargs), q)
197
198 def test_reconstruct_xor(self):
199 q1 = Q(price__gt=F("discounted_price"))
200 q2 = Q(price=F("discounted_price"))
201 q = q1 ^ q2
202 path, args, kwargs = q.deconstruct()
203 self.assertEqual(Q(*args, **kwargs), q)
204
205 def test_reconstruct_and(self):
206 q1 = Q(price__gt=F("discounted_price"))
207 q2 = Q(price=F("discounted_price"))
208 q = q1 & q2
209 path, args, kwargs = q.deconstruct()
210 self.assertEqual(Q(*args, **kwargs), q)
211
212 def test_equal(self):
213 self.assertEqual(Q(), Q())
214 self.assertEqual(
215 Q(("pk__in", (1, 2))),
216 Q(("pk__in", [1, 2])),
217 )
218 self.assertEqual(
219 Q(("pk__in", (1, 2))),
220 Q(pk__in=[1, 2]),
221 )
222 self.assertEqual(
223 Q(("pk__in", (1, 2))),
224 Q(("pk__in", {1: "first", 2: "second"}.keys())),
225 )
226 self.assertNotEqual(
227 Q(name__iexact=F("other_name")),
228 Q(name=Lower(F("other_name"))),
229 )
230
231 def test_hash(self):
232 self.assertEqual(hash(Q()), hash(Q()))
233 self.assertEqual(
234 hash(Q(("pk__in", (1, 2)))),
235 hash(Q(("pk__in", [1, 2]))),
236 )
237 self.assertEqual(
238 hash(Q(("pk__in", (1, 2)))),
239 hash(Q(pk__in=[1, 2])),
240 )
241 self.assertEqual(
242 hash(Q(("pk__in", (1, 2)))),
243 hash(Q(("pk__in", {1: "first", 2: "second"}.keys()))),
244 )
245 self.assertNotEqual(
246 hash(Q(name__iexact=F("other_name"))),
247 hash(Q(name=Lower(F("other_name")))),
248 )
249
250 def test_flatten(self):
251 q = Q()
252 self.assertEqual(list(q.flatten()), [q])
253 q = Q(NothingNode())
254 self.assertEqual(list(q.flatten()), [q, q.children[0]])
255 q = Q(
256 ExpressionWrapper(
257 Q(RawSQL("id = 0", params=(), output_field=BooleanField()))
258 | Q(price=Value("4.55"))
259 | Q(name=Lower("category")),
260 output_field=BooleanField(),
261 )
262 )
263 flatten = list(q.flatten())
264 self.assertEqual(len(flatten), 7)
265
266 def test_create_helper(self):
267 items = [("a", 1), ("b", 2), ("c", 3)]
268 for connector in [Q.AND, Q.OR, Q.XOR]:
269 with self.subTest(connector=connector):
270 self.assertEqual(
271 Q.create(items, connector=connector),
272 Q(*items, _connector=connector),
273 )
274
275 def test_connector_validation(self):
276 msg = f"_connector must be one of {Q.AND!r}, {Q.OR!r}, {Q.XOR!r}, or None."
277 with self.assertRaisesMessage(ValueError, msg):
278 Q(_connector="evil")
279
280 def test_referenced_base_fields(self):
281 # Make sure Q.referenced_base_fields retrieves all base fields from
282 # both filters and F expressions.
283 tests = [
284 (Q(field_1=1) & Q(field_2=1), {"field_1", "field_2"}),
285 (
286 Q(Exact(F("field_3"), IsNull(F("field_4"), True))),
287 {"field_3", "field_4"},
288 ),
289 (Q(Exact(Q(field_5=F("field_6")), True)), {"field_5", "field_6"}),
290 (Q(field_2=1), {"field_2"}),
291 (Q(field_7__lookup=True), {"field_7"}),
292 (Q(field_7__joined_field__lookup=True), {"field_7"}),
293 ]
294 combined_q = Q(1)
295 combined_q_base_fields = set()
296 for q, expected_base_fields in tests:
297 combined_q &= q
298 combined_q_base_fields |= expected_base_fields
299 tests.append((combined_q, combined_q_base_fields))
300 for q, expected_base_fields in tests:
301 with self.subTest(q=q):
302 self.assertEqual(
303 q.referenced_base_fields,
304 expected_base_fields,
305 )
306
307 def test_replace_expressions(self):
308 replacements = {F("timestamp"): Value(None)}
309 self.assertEqual(
310 Q(timestamp__date__day=25).replace_expressions(replacements),
311 Q(timestamp__date__day=25),
312 )
313 replacements = {F("timestamp"): Value(datetime(2025, 10, 23))}
314 self.assertEqual(
315 Q(timestamp__date__day=13).replace_expressions(replacements),
316 Q(
317 IntegerFieldExact(
318 ExtractDay(TruncDate(Value(datetime(2025, 10, 23)))),
319 13,
320 )
321 ),
322 )
323 self.assertEqual(
324 Q(timestamp__date__day__lte=25).replace_expressions(replacements),
325 Q(
326 IntegerLessThanOrEqual(
327 ExtractDay(TruncDate(Value(datetime(2025, 10, 23)))),
328 25,
329 )
330 ),
331 )
332 self.assertEqual(
333 (
334 Q(Q(timestamp__date__day__lte=25), timestamp__date__day=13)
335 ).replace_expressions(replacements),
336 (
337 Q(
338 Q(
339 IntegerLessThanOrEqual(
340 ExtractDay(TruncDate(Value(datetime(2025, 10, 23)))),
341 25,
342 )
343 ),
344 IntegerFieldExact(
345 ExtractDay(TruncDate(Value(datetime(2025, 10, 23)))),
346 13,
347 ),
348 )
349 ),
350 )
351 self.assertEqual(
352 Q(timestamp=None).replace_expressions(replacements),
353 Q(IsNull(Value(datetime(2025, 10, 23)), True)),
354 )
355 self.assertEqual(
356 Q(timestamp__date__day__invalid=25).replace_expressions(replacements),
357 Q(timestamp__date__day__invalid=25),
358 )
359
360
361 class QCheckTests(TestCase):
362 def test_basic(self):
363 q = Q(price__gt=20)
364 self.assertIs(q.check({"price": 30}), True)
365 self.assertIs(q.check({"price": 10}), False)
366
367 def test_expression(self):
368 q = Q(name="test")
369 self.assertIs(q.check({"name": Lower(Value("TeSt"))}), True)
370 self.assertIs(q.check({"name": Value("other")}), False)
371
372 def test_missing_field(self):
373 q = Q(description__startswith="prefix")
374 msg = "Cannot resolve keyword 'description' into field."
375 with self.assertRaisesMessage(FieldError, msg):
376 q.check({"name": "test"})
377
378 def test_boolean_expression(self):
379 q = Q(ExpressionWrapper(Q(price__gt=20), output_field=BooleanField()))
380 self.assertIs(q.check({"price": 25}), True)
381 self.assertIs(q.check({"price": Value(10)}), False)
382
383 def test_rawsql(self):
384 """
385 RawSQL expressions cause a database error because "price" cannot be
386 replaced by its value. In this case, Q.check() logs a warning and
387 return True.
388 """
389 q = Q(RawSQL("price > %s", params=(20,), output_field=BooleanField()))
390 with self.assertLogs("django.db.models", "WARNING") as cm:
391 self.assertIs(q.check({"price": 10}), True)
392 self.assertIn(
393 f"Got a database error calling check() on {q!r}: ",
394 cm.records[0].getMessage(),
395 )
396
397 # We must leave the connection in a usable state (#35712).
398 self.assertTrue(connection.is_usable())