Ticket #27498: tests.py

File tests.py, 1.7 KB (added by Tim Düllmann, 7 years ago)
Line 
1from django.db import connection
2from django.db.models import Sum, F, Case, When
3from django.test import TestCase
4from .models import Product, Stock
5
6
7class ErrorTestCase(TestCase):
8 def setUp(self):
9 p1 = Product.objects.create(name="Product1", qty_target=10)
10 p2 = Product.objects.create(name="Product2", qty_target=10)
11 p3 = Product.objects.create(name="Product3", qty_target=10)
12
13 s1 = Stock.objects.create(product=p1, qty_available=5)
14 s2 = Stock.objects.create(product=p1, qty_available=5)
15 s3 = Stock.objects.create(product=p1, qty_available=3) # 3 over target
16
17 s4 = Stock.objects.create(product=p2, qty_available=5)
18 s5 = Stock.objects.create(product=p2, qty_available=4) # 1 under target
19
20 s6 = Stock.objects.create(product=p3, qty_available=0) # 10 under target
21
22 def testError(self):
23 qs = Product.objects.annotate(qty_available_sum=Sum('stock__qty_available')) \
24 .annotate(qty_needed=F('qty_target') - F('qty_available_sum')) \
25 .filter(qty_needed__gt=0)
26
27 # Query:
28 print()
29 query = str(qs.query)
30 print("# Query from QuerySet:")
31 print(query)
32 rows = []
33 with connection.cursor() as cursor:
34 cursor.execute(query)
35 rows = cursor.fetchall()
36 print("# Results from above Query:")
37 for r in rows:
38 print(r)
39 self.assertEqual(len(rows), 2, "Two products need stock by SQL query.")
40
41 # QuerySet:
42 print()
43 print("# Results from QuerySet:")
44 for q in qs:
45 print(q, q.qty_needed)
46 self.assertEqual(qs.count(), 2, "Two products need stock by Django QuerySet.")
Back to Top