forked from coleifer/peewee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
1820 lines (1402 loc) · 65.5 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding=utf-8
from __future__ import with_statement
import datetime
import decimal
import logging
import os
import Queue
import threading
import unittest
from peewee import *
from peewee import QueryCompiler, R, SelectQuery, RawQuery, InsertQuery,\
UpdateQuery, DeleteQuery, logger, transaction, sort_models_topologically
class QueryLogHandler(logging.Handler):
def __init__(self, *args, **kwargs):
self.queries = []
logging.Handler.__init__(self, *args, **kwargs)
def emit(self, record):
self.queries.append(record)
#
# JUNK TO ALLOW TESTING OF MULTIPLE DATABASE BACKENDS
#
BACKEND = os.environ.get('PEEWEE_TEST_BACKEND', 'sqlite')
TEST_VERBOSITY = int(os.environ.get('PEEWEE_TEST_VERBOSITY') or 1)
database_params = {}
if BACKEND == 'postgresql':
database_class = PostgresqlDatabase
database_name = 'peewee_test'
elif BACKEND == 'mysql':
database_class = MySQLDatabase
database_name = 'peewee_test'
elif BACKEND == 'apsw':
from extras.apsw_ext import *
database_class = APSWDatabase
database_name = 'tmp.db'
database_params['timeout'] = 1000
else:
database_class = SqliteDatabase
database_name = 'tmp.db'
import sqlite3
print 'SQLITE VERSION: %s' % sqlite3.version
#
# TEST-ONLY QUERY COMPILER USED TO CREATE "predictable" QUERIES
#
class TestQueryCompiler(QueryCompiler):
def _max_alias(self, am):
return 0
def calculate_alias_map(self, query, start=1):
alias_map = {query.model_class: query.model_class._meta.db_table}
for model, joins in query._joins.items():
if model not in alias_map:
alias_map[model] = model._meta.db_table
for join in joins:
if join.model_class not in alias_map:
alias_map[join.model_class] = join.model_class._meta.db_table
return alias_map
class TestDatabase(database_class):
compiler_class = TestQueryCompiler
field_overrides = {}
interpolation = '?'
op_overrides = {}
quote_char = '"'
test_db = database_class(database_name, **database_params)
query_db = TestDatabase(database_name, **database_params)
compiler = query_db.get_compiler()
#
# BASE MODEL CLASS
#
class TestModel(Model):
class Meta:
database = test_db
#
# MODEL CLASSES USED BY TEST CASES
#
class User(TestModel):
username = CharField()
class Meta:
db_table = 'users'
class Blog(TestModel):
user = ForeignKeyField(User)
title = CharField(max_length=25)
content = TextField(default='')
pub_date = DateTimeField(null=True)
pk = PrimaryKeyField()
def __unicode__(self):
return '%s: %s' % (self.user.username, self.title)
class Comment(TestModel):
blog = ForeignKeyField(Blog, related_name='comments')
comment = CharField()
class Relationship(TestModel):
from_user = ForeignKeyField(User, related_name='relationships')
to_user = ForeignKeyField(User, related_name='related_to')
class NullModel(TestModel):
char_field = CharField(null=True)
text_field = TextField(null=True)
datetime_field = DateTimeField(null=True)
int_field = IntegerField(null=True)
float_field = FloatField(null=True)
decimal_field1 = DecimalField(null=True)
decimal_field2 = DecimalField(decimal_places=2, null=True)
double_field = DoubleField(null=True)
bigint_field = BigIntegerField(null=True)
date_field = DateField(null=True)
time_field = TimeField(null=True)
boolean_field = BooleanField(null=True)
class UniqueModel(TestModel):
name = CharField(unique=True)
class OrderedModel(TestModel):
title = CharField()
created = DateTimeField(default=datetime.datetime.now)
class Meta:
order_by = ('-created',)
class Category(TestModel):
parent = ForeignKeyField('self', related_name='children', null=True)
name = CharField()
class UserCategory(TestModel):
user = ForeignKeyField(User)
category = ForeignKeyField(Category)
class NonIntModel(TestModel):
pk = CharField(primary_key=True)
data = CharField()
class NonIntRelModel(TestModel):
non_int_model = ForeignKeyField(NonIntModel, related_name='nr')
class DBUser(TestModel):
user_id = PrimaryKeyField(db_column='db_user_id')
username = CharField(db_column='db_username')
class DBBlog(TestModel):
blog_id = PrimaryKeyField(db_column='db_blog_id')
title = CharField(db_column='db_title')
user = ForeignKeyField(DBUser, db_column='db_user')
class SeqModelA(TestModel):
id = IntegerField(primary_key=True, sequence='just_testing_seq')
num = IntegerField()
class SeqModelB(TestModel):
id = IntegerField(primary_key=True, sequence='just_testing_seq')
other_num = IntegerField()
class MultiIndexModel(TestModel):
f1 = CharField()
f2 = CharField()
f3 = CharField()
class Meta:
indexes = (
(('f1', 'f2'), True),
(('f2', 'f3'), False),
)
class BlogTwo(Blog):
title = TextField()
extra_field = CharField()
class Parent(TestModel):
data = CharField()
class Child(TestModel):
parent = ForeignKeyField(Parent)
class Orphan(TestModel):
parent = ForeignKeyField(Parent, null=True)
class ChildPet(TestModel):
child = ForeignKeyField(Child)
class OrphanPet(TestModel):
orphan = ForeignKeyField(Orphan)
MODELS = [User, Blog, Comment, Relationship, NullModel, UniqueModel, OrderedModel, Category, UserCategory,
NonIntModel, NonIntRelModel, DBUser, DBBlog, SeqModelA, SeqModelB, MultiIndexModel, BlogTwo]
INT = test_db.interpolation
def drop_tables(only=None):
for model in reversed(MODELS):
if only is None or model in only:
model.drop_table(True)
def create_tables(only=None):
for model in MODELS:
if only is None or model in only:
model.create_table()
#
# BASE TEST CASE USED BY ALL TESTS
#
class BasePeeweeTestCase(unittest.TestCase):
def setUp(self):
self.qh = QueryLogHandler()
logger.setLevel(logging.DEBUG)
logger.addHandler(self.qh)
def tearDown(self):
logger.removeHandler(self.qh)
def queries(self):
return [x.msg for x in self.qh.queries]
def parse_expr(self, query, expr_list):
am = compiler.calculate_alias_map(query)
return compiler.parse_expr_list(expr_list, am)
def parse_node(self, query, node):
am = compiler.calculate_alias_map(query)
return compiler.parse_query_node(node, am)
def make_fn(fn_name, attr_name):
def inner(self, query, expected, expected_params):
fn = getattr(self, fn_name)
att = getattr(query, attr_name)
sql, params = fn(query, att)
self.assertEqual(sql, expected)
self.assertEqual(params, expected_params)
return inner
assertSelect = make_fn('parse_expr', '_select')
assertWhere = make_fn('parse_node', '_where')
assertGroupBy = make_fn('parse_expr', '_group_by')
assertHaving = make_fn('parse_node', '_having')
assertOrderBy = make_fn('parse_expr', '_order_by')
def assertJoins(self, sq, exp_joins):
am = compiler.calculate_alias_map(sq)
joins = compiler.parse_joins(sq._joins, sq.model_class, am)
self.assertEqual(sorted(joins), sorted(exp_joins))
def assertDict(self, qd, expected, expected_params):
sets, params = compiler._parse_field_dictionary(qd)
self.assertEqual(sets, expected)
self.assertEqual(params, expected_params)
def assertUpdate(self, uq, expected, expected_params):
self.assertDict(uq._update, expected, expected_params)
def assertInsert(self, uq, expected, expected_params):
self.assertDict(uq._insert, expected, expected_params)
#
# BASIC TESTS OF QUERY TYPES AND INTERNAL DATA STRUCTURES
#
class SelectTestCase(BasePeeweeTestCase):
def test_selection(self):
sq = SelectQuery(User)
self.assertSelect(sq, 'users."id", users."username"', [])
sq = SelectQuery(Blog, Blog.pk, Blog.title, Blog.user, User.username).join(User)
self.assertSelect(sq, 'blog."pk", blog."title", blog."user_id", users."username"', [])
sq = SelectQuery(User, fn.Lower(fn.Substr(User.username, 0, 1)).alias('lu'), fn.Count(Blog.pk)).join(Blog)
self.assertSelect(sq, 'Lower(Substr(users."username", ?, ?)) AS lu, Count(blog."pk")', [0, 1])
sq = SelectQuery(User, User.username, fn.Count(Blog.select().where(Blog.user == User.id)))
self.assertSelect(sq, 'users."username", Count((SELECT blog."pk" FROM "blog" AS blog WHERE (blog."user_id" = users."id")))', [])
def test_joins(self):
sq = SelectQuery(User).join(Blog)
self.assertJoins(sq, ['INNER JOIN "blog" AS blog ON users."id" = blog."user_id"'])
sq = SelectQuery(Blog).join(User, JOIN_LEFT_OUTER)
self.assertJoins(sq, ['LEFT OUTER JOIN "users" AS users ON blog."user_id" = users."id"'])
sq = SelectQuery(User).join(Relationship)
self.assertJoins(sq, ['INNER JOIN "relationship" AS relationship ON users."id" = relationship."from_user_id"'])
sq = SelectQuery(User).join(Relationship, on=Relationship.to_user)
self.assertJoins(sq, ['INNER JOIN "relationship" AS relationship ON users."id" = relationship."to_user_id"'])
sq = SelectQuery(User).join(Relationship, JOIN_LEFT_OUTER, Relationship.to_user)
self.assertJoins(sq, ['LEFT OUTER JOIN "relationship" AS relationship ON users."id" = relationship."to_user_id"'])
def test_join_self_referential(self):
sq = SelectQuery(Category).join(Category)
self.assertJoins(sq, ['INNER JOIN "category" AS category ON category."parent_id" = category."id"'])
def test_join_both_sides(self):
sq = SelectQuery(Blog).join(Comment).switch(Blog).join(User)
self.assertJoins(sq, [
'INNER JOIN "comment" AS comment ON blog."pk" = comment."blog_id"',
'INNER JOIN "users" AS users ON blog."user_id" = users."id"',
])
sq = SelectQuery(Blog).join(User).switch(Blog).join(Comment)
self.assertJoins(sq, [
'INNER JOIN "users" AS users ON blog."user_id" = users."id"',
'INNER JOIN "comment" AS comment ON blog."pk" = comment."blog_id"',
])
def test_join_switching(self):
class Artist(TestModel):
pass
class Track(TestModel):
artist = ForeignKeyField(Artist)
class Release(TestModel):
artist = ForeignKeyField(Artist)
class ReleaseTrack(TestModel):
track = ForeignKeyField(Track)
release = ForeignKeyField(Release)
class Genre(TestModel):
pass
class TrackGenre(TestModel):
genre = ForeignKeyField(Genre)
track = ForeignKeyField(Track)
multiple_first = Track.select().join(ReleaseTrack).join(Release).switch(Track).join(Artist).switch(Track).join(TrackGenre).join(Genre)
self.assertSelect(multiple_first, 'track."id", track."artist_id"', [])
self.assertJoins(multiple_first, [
'INNER JOIN "artist" AS artist ON track."artist_id" = artist."id"',
'INNER JOIN "genre" AS genre ON trackgenre."genre_id" = genre."id"',
'INNER JOIN "release" AS release ON releasetrack."release_id" = release."id"',
'INNER JOIN "releasetrack" AS releasetrack ON track."id" = releasetrack."track_id"',
'INNER JOIN "trackgenre" AS trackgenre ON track."id" = trackgenre."track_id"',
])
single_first = Track.select().join(Artist).switch(Track).join(ReleaseTrack).join(Release).switch(Track).join(TrackGenre).join(Genre)
self.assertSelect(single_first, 'track."id", track."artist_id"', [])
self.assertJoins(single_first, [
'INNER JOIN "artist" AS artist ON track."artist_id" = artist."id"',
'INNER JOIN "genre" AS genre ON trackgenre."genre_id" = genre."id"',
'INNER JOIN "release" AS release ON releasetrack."release_id" = release."id"',
'INNER JOIN "releasetrack" AS releasetrack ON track."id" = releasetrack."track_id"',
'INNER JOIN "trackgenre" AS trackgenre ON track."id" = trackgenre."track_id"',
])
def test_where(self):
sq = SelectQuery(User).where(User.id < 5)
self.assertWhere(sq, '(users."id" < ?)', [5])
def test_where_lists(self):
sq = SelectQuery(User).where(User.username << ['u1', 'u2'])
self.assertWhere(sq, '(users."username" IN (?,?))', ['u1', 'u2'])
sq = SelectQuery(User).where((User.username << ['u1', 'u2']) | (User.username << ['u3', 'u4']))
self.assertWhere(sq, '((users."username" IN (?,?)) OR (users."username" IN (?,?)))', ['u1', 'u2', 'u3', 'u4'])
def test_where_joins(self):
sq = SelectQuery(User).where(
((User.id == 1) | (User.id == 2)) &
((Blog.pk == 3) | (Blog.pk == 4))
).where(User.id == 5).join(Blog)
self.assertWhere(sq, '((((users."id" = ?) OR (users."id" = ?)) AND ((blog."pk" = ?) OR (blog."pk" = ?))) AND (users."id" = ?))', [1, 2, 3, 4, 5])
def test_where_functions(self):
sq = SelectQuery(User).where(fn.Lower(fn.Substr(User.username, 0, 1)) == 'a')
self.assertWhere(sq, '(Lower(Substr(users."username", ?, ?)) = ?)', [0, 1, 'a'])
def test_where_subqueries(self):
sq = SelectQuery(User).where(User.id << User.select().where(User.username=='u1'))
self.assertWhere(sq, '(users."id" IN (SELECT users."id" FROM "users" AS users WHERE (users."username" = ?)))', ['u1'])
sq = SelectQuery(Blog).where((Blog.pk == 3) | (Blog.user << User.select().where(User.username << ['u1', 'u2'])))
self.assertWhere(sq, '((blog."pk" = ?) OR (blog."user_id" IN (SELECT users."id" FROM "users" AS users WHERE (users."username" IN (?,?)))))', [3, 'u1', 'u2'])
def test_where_fk(self):
sq = SelectQuery(Blog).where(Blog.user == User(id=100))
self.assertWhere(sq, '(blog."user_id" = ?)', [100])
sq = SelectQuery(Blog).where(Blog.user << [User(id=100), User(id=101)])
self.assertWhere(sq, '(blog."user_id" IN (?,?))', [100, 101])
def test_where_negation(self):
sq = SelectQuery(Blog).where(~(Blog.title == 'foo'))
self.assertWhere(sq, 'NOT (blog."title" = ?)', ['foo'])
sq = SelectQuery(Blog).where(~((Blog.title == 'foo') | (Blog.title == 'bar')))
self.assertWhere(sq, 'NOT ((blog."title" = ?) OR (blog."title" = ?))', ['foo', 'bar'])
sq = SelectQuery(Blog).where(~((Blog.title == 'foo') & (Blog.title == 'bar')) & (Blog.title == 'baz'))
self.assertWhere(sq, '(NOT ((blog."title" = ?) AND (blog."title" = ?)) AND (blog."title" = ?))', ['foo', 'bar', 'baz'])
sq = SelectQuery(Blog).where(~((Blog.title == 'foo') & (Blog.title == 'bar')) & ((Blog.title == 'baz') & (Blog.title == 'fizz')))
self.assertWhere(sq, '(NOT ((blog."title" = ?) AND (blog."title" = ?)) AND ((blog."title" = ?) AND (blog."title" = ?)))', ['foo', 'bar', 'baz', 'fizz'])
def test_where_chaining_collapsing(self):
sq = SelectQuery(User).where(User.id == 1).where(User.id == 2).where(User.id == 3)
self.assertWhere(sq, '(((users."id" = ?) AND (users."id" = ?)) AND (users."id" = ?))', [1, 2, 3])
sq = SelectQuery(User).where((User.id == 1) & (User.id == 2)).where(User.id == 3)
self.assertWhere(sq, '(((users."id" = ?) AND (users."id" = ?)) AND (users."id" = ?))', [1, 2, 3])
sq = SelectQuery(User).where((User.id == 1) | (User.id == 2)).where(User.id == 3)
self.assertWhere(sq, '(((users."id" = ?) OR (users."id" = ?)) AND (users."id" = ?))', [1, 2, 3])
sq = SelectQuery(User).where(User.id == 1).where((User.id == 2) & (User.id == 3))
self.assertWhere(sq, '((users."id" = ?) AND ((users."id" = ?) AND (users."id" = ?)))', [1, 2, 3])
sq = SelectQuery(User).where(User.id == 1).where((User.id == 2) | (User.id == 3))
self.assertWhere(sq, '((users."id" = ?) AND ((users."id" = ?) OR (users."id" = ?)))', [1, 2, 3])
sq = SelectQuery(User).where(~(User.id == 1)).where(User.id == 2).where(~(User.id == 3))
self.assertWhere(sq, '((NOT (users."id" = ?) AND (users."id" = ?)) AND NOT (users."id" = ?))', [1, 2, 3])
def test_grouping(self):
sq = SelectQuery(User).group_by(User.id)
self.assertGroupBy(sq, 'users."id"', [])
sq = SelectQuery(User).group_by(User)
self.assertGroupBy(sq, 'users."id", users."username"', [])
def test_having(self):
sq = SelectQuery(User, fn.Count(Blog.pk)).join(Blog).group_by(User).having(
fn.Count(Blog.pk) > 2
)
self.assertHaving(sq, '(Count(blog."pk") > ?)', [2])
sq = SelectQuery(User, fn.Count(Blog.pk)).join(Blog).group_by(User).having(
(fn.Count(Blog.pk) > 10) | (fn.Count(Blog.pk) < 2)
)
self.assertHaving(sq, '((Count(blog."pk") > ?) OR (Count(blog."pk") < ?))', [10, 2])
def test_ordering(self):
sq = SelectQuery(User).join(Blog).order_by(Blog.title)
self.assertOrderBy(sq, 'blog."title"', [])
sq = SelectQuery(User).join(Blog).order_by(Blog.title.asc())
self.assertOrderBy(sq, 'blog."title" ASC', [])
sq = SelectQuery(User).join(Blog).order_by(Blog.title.desc())
self.assertOrderBy(sq, 'blog."title" DESC', [])
sq = SelectQuery(User).join(Blog).order_by(User.username.desc(), Blog.title.asc())
self.assertOrderBy(sq, 'users."username" DESC, blog."title" ASC', [])
base_sq = SelectQuery(User, User.username, fn.Count(Blog.pk).alias('count')).join(Blog).group_by(User.username)
sq = base_sq.order_by(fn.Count(Blog.pk).desc())
self.assertOrderBy(sq, 'Count(blog."pk") DESC', [])
sq = base_sq.order_by(R('count'))
self.assertOrderBy(sq, 'count', [])
sq = OrderedModel.select()
self.assertOrderBy(sq, 'orderedmodel."created" DESC', [])
sq = OrderedModel.select().order_by(OrderedModel.id.asc())
self.assertOrderBy(sq, 'orderedmodel."id" ASC', [])
def test_paginate(self):
sq = SelectQuery(User).paginate(1, 20)
self.assertEqual(sq._limit, 20)
self.assertEqual(sq._offset, 0)
sq = SelectQuery(User).paginate(3, 30)
self.assertEqual(sq._limit, 30)
self.assertEqual(sq._offset, 60)
class UpdateTestCase(BasePeeweeTestCase):
def test_update(self):
uq = UpdateQuery(User, {User.username: 'updated'})
self.assertUpdate(uq, [('"username"', '?')], ['updated'])
uq = UpdateQuery(Blog, {Blog.user: User(id=100, username='foo')})
self.assertUpdate(uq, [('"user_id"', '?')], [100])
uq = UpdateQuery(User, {User.id: User.id + 5})
self.assertUpdate(uq, [('"id"', '("id" + ?)')], [5])
uq = UpdateQuery(User, {User.id: 5 * (3 + User.id)})
self.assertUpdate(uq, [('"id"', '(? * (? + "id"))')], [5, 3])
def test_where(self):
uq = UpdateQuery(User, {User.username: 'updated'}).where(User.id == 2)
self.assertWhere(uq, '(users."id" = ?)', [2])
class InsertTestCase(BasePeeweeTestCase):
def test_insert(self):
iq = InsertQuery(User, {User.username: 'inserted'})
self.assertInsert(iq, [('"username"', '?')], ['inserted'])
class DeleteTestCase(BasePeeweeTestCase):
def test_where(self):
dq = DeleteQuery(User).where(User.id == 2)
self.assertWhere(dq, '(users."id" = ?)', [2])
class RawTestCase(BasePeeweeTestCase):
def test_raw(self):
q = 'SELECT * FROM "users" WHERE id=?'
rq = RawQuery(User, q, 100)
self.assertEqual(rq.sql(compiler), (q, [100]))
class SugarTestCase(BasePeeweeTestCase):
# test things like filter, annotate, aggregate
def test_filter(self):
sq = User.filter(username='u1')
self.assertJoins(sq, [])
self.assertWhere(sq, '(users."username" = ?)', ['u1'])
sq = Blog.filter(user__username='u1')
self.assertJoins(sq, ['INNER JOIN "users" AS users ON blog."user_id" = users."id"'])
self.assertWhere(sq, '(users."username" = ?)', ['u1'])
sq = Blog.filter(user__username__in=['u1', 'u2'], comments__comment='hurp')
self.assertJoins(sq, [
'INNER JOIN "comment" AS comment ON blog."pk" = comment."blog_id"',
'INNER JOIN "users" AS users ON blog."user_id" = users."id"',
])
self.assertWhere(sq, '((comment."comment" = ?) AND (users."username" IN (?,?)))', ['hurp', 'u1', 'u2'])
sq = Blog.filter(user__username__in=['u1', 'u2']).filter(comments__comment='hurp')
self.assertJoins(sq, [
'INNER JOIN "users" AS users ON blog."user_id" = users."id"',
'INNER JOIN "comment" AS comment ON blog."pk" = comment."blog_id"',
])
self.assertWhere(sq, '((users."username" IN (?,?)) AND (comment."comment" = ?))', ['u1', 'u2', 'hurp'])
def test_filter_dq(self):
sq = User.filter(DQ(username='u1') | DQ(username='u2'))
self.assertJoins(sq, [])
self.assertWhere(sq, '((users."username" = ?) OR (users."username" = ?))', ['u1', 'u2'])
sq = Comment.filter(DQ(blog__user__username='u1') | DQ(blog__title='b1'), DQ(comment='c1'))
self.assertJoins(sq, [
'INNER JOIN "blog" AS blog ON comment."blog_id" = blog."pk"',
'INNER JOIN "users" AS users ON blog."user_id" = users."id"',
])
self.assertWhere(sq, '(((users."username" = ?) OR (blog."title" = ?)) AND (comment."comment" = ?))', ['u1', 'b1', 'c1'])
sq = Blog.filter(DQ(user__username='u1') | DQ(comments__comment='c1'))
self.assertJoins(sq, [
'INNER JOIN "comment" AS comment ON blog."pk" = comment."blog_id"',
'INNER JOIN "users" AS users ON blog."user_id" = users."id"',
])
self.assertWhere(sq, '((users."username" = ?) OR (comment."comment" = ?))', ['u1', 'c1'])
def test_annotate(self):
sq = User.select().annotate(Blog)
self.assertSelect(sq, 'users."id", users."username", Count(blog."pk") AS count', [])
self.assertJoins(sq, ['INNER JOIN "blog" AS blog ON users."id" = blog."user_id"'])
self.assertWhere(sq, '', [])
self.assertGroupBy(sq, 'users."id", users."username"', [])
sq = User.select(User.username).annotate(Blog, fn.Sum(Blog.pk).alias('sum')).where(User.username == 'foo')
self.assertSelect(sq, 'users."username", Sum(blog."pk") AS sum', [])
self.assertJoins(sq, ['INNER JOIN "blog" AS blog ON users."id" = blog."user_id"'])
self.assertWhere(sq, '(users."username" = ?)', ['foo'])
self.assertGroupBy(sq, 'users."username"', [])
sq = User.select(User.username).annotate(Blog).annotate(Blog, fn.Max(Blog.pk).alias('mx'))
self.assertSelect(sq, 'users."username", Count(blog."pk") AS count, Max(blog."pk") AS mx', [])
self.assertJoins(sq, ['INNER JOIN "blog" AS blog ON users."id" = blog."user_id"'])
self.assertWhere(sq, '', [])
self.assertGroupBy(sq, 'users."username"', [])
sq = User.select().annotate(Blog).order_by(R('count DESC'))
self.assertSelect(sq, 'users."id", users."username", Count(blog."pk") AS count', [])
self.assertOrderBy(sq, 'count DESC', [])
sq = User.select().join(Blog, JOIN_LEFT_OUTER).switch(User).annotate(Blog)
self.assertSelect(sq, 'users."id", users."username", Count(blog."pk") AS count', [])
self.assertJoins(sq, ['LEFT OUTER JOIN "blog" AS blog ON users."id" = blog."user_id"'])
self.assertWhere(sq, '', [])
self.assertGroupBy(sq, 'users."id", users."username"', [])
def test_aggregate(self):
sq = User.select().where(User.id < 10)._aggregate()
self.assertSelect(sq, 'Count(users."id")', [])
self.assertWhere(sq, '(users."id" < ?)', [10])
#
# TEST CASE USED TO PROVIDE ACCESS TO DATABASE
# FOR EXECUTION OF "LIVE" QUERIES
#
class ModelTestCase(BasePeeweeTestCase):
requires = None
def setUp(self):
super(ModelTestCase, self).setUp()
drop_tables(self.requires)
create_tables(self.requires)
def tearDown(self):
drop_tables(self.requires)
def create_user(self, username):
return User.create(username=username)
def create_users(self, n):
for i in range(n):
self.create_user('u%d' % (i + 1))
class QueryResultWrapperTestCase(ModelTestCase):
requires = [User, Blog, Comment]
def test_iteration(self):
self.create_users(10)
query_start = len(self.queries())
sq = User.select()
qr = sq.execute()
first_five = []
for i, u in enumerate(qr):
first_five.append(u.username)
if i == 4:
break
self.assertEqual(first_five, ['u1', 'u2', 'u3', 'u4', 'u5'])
another_iter = [u.username for u in qr]
self.assertEqual(another_iter, ['u%d' % i for i in range(1, 11)])
another_iter = [u.username for u in qr]
self.assertEqual(another_iter, ['u%d' % i for i in range(1, 11)])
# only 1 query for these iterations
self.assertEqual(len(self.queries()) - query_start, 1)
def test_iterator(self):
self.create_users(10)
qc = len(self.queries())
qr = User.select().execute()
usernames = [u.username for u in qr.iterator()]
self.assertEqual(usernames, ['u%d' % i for i in range(1, 11)])
qc1 = len(self.queries())
self.assertEqual(qc1 - qc, 1)
self.assertTrue(qr._populated)
self.assertEqual(qr._result_cache, [])
again = [u.username for u in qr]
self.assertEqual(again, [])
qc2 = len(self.queries())
self.assertEqual(qc2 - qc1, 0)
qr = User.select().where(User.username == 'xxx').execute()
usernames = [u.username for u in qr.iterator()]
self.assertEqual(usernames, [])
def test_select_related(self):
u1 = User.create(username='u1')
u2 = User.create(username='u2')
b1 = Blog.create(user=u1, title='b1')
b2 = Blog.create(user=u2, title='b2')
c11 = Comment.create(blog=b1, comment='c11')
c12 = Comment.create(blog=b1, comment='c12')
c21 = Comment.create(blog=b2, comment='c21')
c22 = Comment.create(blog=b2, comment='c22')
# missing comment.blog_id
qc = len(self.queries())
comments = Comment.select(Comment.id, Comment.comment, Blog.pk, Blog.title).join(Blog).where(Blog.title == 'b1').order_by(Comment.id)
self.assertEqual([c.blog.title for c in comments], ['b1', 'b1'])
self.assertEqual(len(self.queries()) - qc, 1)
# missing blog.pk
qc = len(self.queries())
comments = Comment.select(Comment.id, Comment.comment, Comment.blog, Blog.title).join(Blog).where(Blog.title == 'b2').order_by(Comment.id)
self.assertEqual([c.blog.title for c in comments], ['b2', 'b2'])
self.assertEqual(len(self.queries()) - qc, 1)
# both but going up 2 levels
qc = len(self.queries())
comments = Comment.select(Comment, Blog, User).join(Blog).join(User).where(User.username == 'u1').order_by(Comment.id)
self.assertEqual([c.comment for c in comments], ['c11', 'c12'])
self.assertEqual([c.blog.title for c in comments], ['b1', 'b1'])
self.assertEqual([c.blog.user.username for c in comments], ['u1', 'u1'])
self.assertEqual(len(self.queries()) - qc, 1)
qc = len(self.queries())
comments = Comment.select().join(Blog).join(User).where(User.username == 'u1').order_by(Comment.id)
self.assertEqual([c.blog.user.username for c in comments], ['u1', 'u1'])
self.assertEqual(len(self.queries()) - qc, 5)
def test_naive(self):
u1 = User.create(username='u1')
u2 = User.create(username='u2')
b1 = Blog.create(user=u1, title='b1')
b2 = Blog.create(user=u2, title='b2')
users = User.select().naive()
self.assertEqual([u.username for u in users], ['u1', 'u2'])
users = User.select(User, Blog).join(Blog).naive()
self.assertEqual([u.username for u in users], ['u1', 'u2'])
self.assertEqual([u.title for u in users], ['b1', 'b2'])
class ModelQueryTestCase(ModelTestCase):
requires = [User, Blog]
def create_users_blogs(self, n=10, nb=5):
for i in range(n):
u = User.create(username='u%d' % i)
for j in range(nb):
b = Blog.create(title='b-%d-%d' % (i, j), content=str(j), user=u)
def test_select(self):
self.create_users_blogs()
users = User.select().where(User.username << ['u0', 'u5']).order_by(User.username)
self.assertEqual([u.username for u in users], ['u0', 'u5'])
blogs = Blog.select().join(User).where(
(User.username << ['u0', 'u3']) &
(Blog.content == '4')
).order_by(Blog.title)
self.assertEqual([b.title for b in blogs], ['b-0-4', 'b-3-4'])
users = User.select().paginate(2, 3)
self.assertEqual([u.username for u in users], ['u3', 'u4', 'u5'])
def test_update(self):
self.create_users(5)
uq = User.update(username='u-edited').where(User.username << ['u1', 'u2', 'u3'])
self.assertEqual([u.username for u in User.select().order_by(User.id)], ['u1', 'u2', 'u3', 'u4', 'u5'])
uq.execute()
self.assertEqual([u.username for u in User.select().order_by(User.id)], ['u-edited', 'u-edited', 'u-edited', 'u4', 'u5'])
def test_insert(self):
iq = User.insert(username='u1')
self.assertEqual(User.select().count(), 0)
uid = iq.execute()
self.assertTrue(uid > 0)
self.assertEqual(User.select().count(), 1)
u = User.get(User.id==uid)
self.assertEqual(u.username, 'u1')
def test_delete(self):
self.create_users(5)
dq = User.delete().where(User.username << ['u1', 'u2', 'u3'])
self.assertEqual(User.select().count(), 5)
nr = dq.execute()
self.assertEqual(nr, 3)
self.assertEqual([u.username for u in User.select()], ['u4', 'u5'])
def test_raw(self):
self.create_users(3)
qc = len(self.queries())
rq = User.raw('select * from users where username IN (%s,%s)' % (INT,INT), 'u1', 'u3')
self.assertEqual([u.username for u in rq], ['u1', 'u3'])
# iterate again
self.assertEqual([u.username for u in rq], ['u1', 'u3'])
self.assertEqual(len(self.queries()) - qc, 1)
rq = User.raw('select id, username, %s as secret from users where username = %s' % (INT,INT), 'sh', 'u2')
self.assertEqual([u.secret for u in rq], ['sh'])
self.assertEqual([u.username for u in rq], ['u2'])
class ModelAPITestCase(ModelTestCase):
requires = [User, Blog, Category, UserCategory]
def test_related_name(self):
u1 = self.create_user('u1')
u2 = self.create_user('u2')
b11 = Blog.create(user=u1, title='b11')
b12 = Blog.create(user=u1, title='b12')
b2 = Blog.create(user=u2, title='b2')
self.assertEqual([b.title for b in u1.blog_set], ['b11', 'b12'])
self.assertEqual([b.title for b in u2.blog_set], ['b2'])
def test_fk_exceptions(self):
c1 = Category.create(name='c1')
c2 = Category.create(parent=c1, name='c2')
self.assertEqual(c1.parent, None)
self.assertEqual(c2.parent, c1)
c2_db = Category.get(Category.id == c2.id)
self.assertEqual(c2_db.parent, c1)
u = self.create_user('u1')
b = Blog.create(user=u, title='b')
b2 = Blog(title='b2')
self.assertEqual(b.user, u)
self.assertRaises(User.DoesNotExist, getattr, b2, 'user')
def test_fk_ints(self):
c1 = Category.create(name='c1')
c2 = Category.create(name='c2', parent=c1.id)
c2_db = Category.get(Category.id == c2.id)
self.assertEqual(c2_db.parent, c1)
def test_fk_caching(self):
c1 = Category.create(name='c1')
c2 = Category.create(name='c2', parent=c1)
c2_db = Category.get(Category.id == c2.id)
qc = len(self.queries())
parent = c2_db.parent
self.assertEqual(parent, c1)
parent = c2_db.parent
self.assertEqual(len(self.queries()) - qc, 1)
def test_creation(self):
self.create_users(10)
self.assertEqual(User.select().count(), 10)
def test_saving(self):
self.assertEqual(User.select().count(), 0)
u = User(username='u1')
u.save()
u.save()
self.assertEqual(User.select().count(), 1)
def test_saving_via_create_gh111(self):
u = User.create(username='u')
b = Blog.create(title='foo', user=u)
last_sql, _ = self.queries()[-1]
self.assertFalse('pub_date' in last_sql)
self.assertEqual(b.pub_date, None)
b2 = Blog(title='foo2', user=u)
b2.save()
last_sql, _ = self.queries()[-1]
self.assertFalse('pub_date' in last_sql)
self.assertEqual(b2.pub_date, None)
def test_reading(self):
u1 = self.create_user('u1')
u2 = self.create_user('u2')
self.assertEqual(u1, User.get(username='u1'))
self.assertEqual(u2, User.get(username='u2'))
self.assertFalse(u1 == u2)
self.assertEqual(u1, User.get(User.username == 'u1'))
self.assertEqual(u2, User.get(User.username == 'u2'))
def test_get_or_create(self):
u1 = User.get_or_create(username='u1')
u1_x = User.get_or_create(username='u1')
self.assertEqual(u1.id, u1_x.id)
self.assertEqual(User.select().count(), 1)
def test_deleting(self):
u1 = self.create_user('u1')
u2 = self.create_user('u2')
self.assertEqual(User.select().count(), 2)
u1.delete_instance()
self.assertEqual(User.select().count(), 1)
self.assertEqual(u2, User.get(User.username=='u2'))
def test_counting(self):
u1 = User.create(username='u1')
u2 = User.create(username='u2')
for u in [u1, u2]:
for i in range(5):
Blog.create(title='b-%s-%s' % (u.username, i), user=u)
uc = User.select().where(User.username == 'u1').join(Blog).count()
self.assertEqual(uc, 5)
uc = User.select().where(User.username == 'u1').join(Blog).distinct().count()
self.assertEqual(uc, 1)
def test_count_transaction(self):
for i in range(10):
self.create_user(username='u%d' % i)
with transaction(test_db):
for user in SelectQuery(User):
for i in range(20):
Blog.create(user=user, title='b-%d-%d' % (user.id, i))
count = SelectQuery(Blog).count()
self.assertEqual(count, 200)
def test_exists(self):
u1 = User.create(username='u1')
self.assertTrue(User.select().where(User.username == 'u1').exists())
self.assertFalse(User.select().where(User.username == 'u2').exists())
def test_unicode(self):
ustr = u'Lýðveldið Ísland'
u = self.create_user(username=ustr)
u2 = User.get(User.username == ustr)
self.assertEqual(u2.username, ustr)
class RecursiveDeleteTestCase(BasePeeweeTestCase):
def setUp(self):
super(RecursiveDeleteTestCase, self).setUp()
Parent.create_table(True)
Child.create_table(True)
Orphan.create_table(True)
ChildPet.create_table(True)
OrphanPet.create_table(True)
p1 = Parent.create(data='p1')
p2 = Parent.create(data='p2')
c11 = Child.create(parent=p1)
c12 = Child.create(parent=p1)
c21 = Child.create(parent=p2)
c22 = Child.create(parent=p2)
o11 = Orphan.create(parent=p1)
o12 = Orphan.create(parent=p1)
o21 = Orphan.create(parent=p2)
o22 = Orphan.create(parent=p2)
ChildPet.create(child=c11)
ChildPet.create(child=c12)
ChildPet.create(child=c21)
ChildPet.create(child=c22)
OrphanPet.create(orphan=o11)
OrphanPet.create(orphan=o12)
OrphanPet.create(orphan=o21)
OrphanPet.create(orphan=o22)
self.p1 = p1
self.p2 = p2
def tearDown(self):
super(RecursiveDeleteTestCase, self).tearDown()
OrphanPet.drop_table()
ChildPet.drop_table()
Orphan.drop_table()
Child.drop_table()
Parent.drop_table()
def test_recursive_update(self):
self.p1.delete_instance(recursive=True)
counts = (
#query,fk,p1,p2,tot
(Child.select(), Child.parent, 0, 2, 2),
(Orphan.select(), Orphan.parent, 0, 2, 4),
(ChildPet.select().join(Child), Child.parent, 0, 2, 2),
(OrphanPet.select().join(Orphan), Orphan.parent, 0, 2, 4),
)
for query, fk, p1_ct, p2_ct, tot in counts:
self.assertEqual(query.where(fk == self.p1).count(), p1_ct)
self.assertEqual(query.where(fk == self.p2).count(), p2_ct)
self.assertEqual(query.count(), tot)
def test_recursive_delete(self):
self.p1.delete_instance(recursive=True, delete_nullable=True)
counts = (
#query,fk,p1,p2,tot
(Child.select(), Child.parent, 0, 2, 2),
(Orphan.select(), Orphan.parent, 0, 2, 2),
(ChildPet.select().join(Child), Child.parent, 0, 2, 2),
(OrphanPet.select().join(Orphan), Orphan.parent, 0, 2, 2),
)
for query, fk, p1_ct, p2_ct, tot in counts:
self.assertEqual(query.where(fk == self.p1).count(), p1_ct)
self.assertEqual(query.where(fk == self.p2).count(), p2_ct)
self.assertEqual(query.count(), tot)
class MultipleFKTestCase(ModelTestCase):
requires = [User, Relationship]
def test_multiple_fks(self):
a = User.create(username='a')
b = User.create(username='b')
c = User.create(username='c')