Repository navigation
Expand file tree
/
Copy pathbase_dao_test.py
More file actions
1708 lines (1415 loc) · 53.3 KB
/
Copy pathbase_dao_test.py
File metadata and controls
1708 lines (1415 loc) · 53.3 KB
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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Integration tests for BaseDAO functionality.
This module contains comprehensive integration tests for the BaseDAO class and its
subclasses, covering database operations, CRUD methods, flexible column support,
column operators, and error handling.
Tests use an in-memory SQLite database for isolation and to replicate the unit test
environment behavior. User model deletions are avoided due to circular dependency
constraints with self-referential foreign keys.
"""
import datetime
import time
import uuid
import pytest
from flask_appbuilder.models.filters import BaseFilter
from flask_appbuilder.security.sqla.models import User
from sqlalchemy import Column, DateTime, Integer, String
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm.session import Session
from superset.daos.base import BaseDAO, ColumnOperator, ColumnOperatorEnum
from superset.daos.chart import ChartDAO
from superset.daos.dashboard import DashboardDAO
from superset.daos.database import DatabaseDAO
from superset.daos.user import UserDAO
from superset.extensions import db
from superset.models.core import Database
from superset.models.dashboard import Dashboard
from superset.models.slice import Slice
from tests.integration_tests.base_tests import subjects_from_users
# Create a test model for comprehensive testing
Base = declarative_base()
class ExampleModel(Base): # type: ignore
__tablename__ = "example_model"
id = Column(Integer, primary_key=True)
uuid = Column(String(36), unique=True, nullable=False)
slug = Column(String(100), unique=True)
name = Column(String(100))
code = Column(String(50), unique=True)
created_on = Column(DateTime, default=datetime.datetime.utcnow)
class ExampleModelDAO(BaseDAO[ExampleModel]):
model_cls = ExampleModel
id_column_name = "id"
base_filter = None
@pytest.fixture(autouse=True)
def mock_g_user(app_context):
"""Mock the flask g.user for security context."""
# Within app context, we can safely mock g
from flask import g
mock_user = User()
mock_user.id = 1
mock_user.username = "test_user"
# Set g.user directly instead of patching
g.user = mock_user
yield
# Clean up
if hasattr(g, "user"):
delattr(g, "user")
# =============================================================================
# Integration Tests - These tests use the actual database
# =============================================================================
def test_column_operator_enum_complete_coverage(user_with_data: Session) -> None:
"""
Test that every single ColumnOperatorEnum operator is covered by tests.
This ensures we have comprehensive test coverage for all operators.
"""
# Simply verify that we can create queries with all operators
for operator in ColumnOperatorEnum:
column_operator = ColumnOperator(
col="username", opr=operator, value="test_value"
)
# Just check it doesn't raise an error
assert column_operator.opr == operator
def test_find_by_id_with_default_column(app_context: Session) -> None:
"""Test find_by_id with default 'id' column."""
# Create a user to test with
user = User(
username="test_find_by_id",
first_name="Test",
last_name="User",
email="test@example.com",
active=True,
)
db.session.add(user)
db.session.commit()
# Find by numeric id
found = UserDAO.find_by_id(user.id, skip_base_filter=True)
assert found is not None
assert found.id == user.id
assert found.username == "test_find_by_id"
# Test with non-existent id
not_found = UserDAO.find_by_id(999999, skip_base_filter=True)
assert not_found is None
def test_find_by_id_with_uuid_column(app_context: Session) -> None:
"""Test find_by_id with custom uuid column."""
# Create a dashboard with uuid
dashboard = Dashboard(
dashboard_title="Test UUID Dashboard",
slug="test-uuid-dashboard",
published=True,
)
db.session.add(dashboard)
db.session.commit()
# Find by uuid string using the uuid column
found = DashboardDAO.find_by_id(
str(dashboard.uuid), id_column="uuid", skip_base_filter=True
)
assert found is not None
assert found.uuid == dashboard.uuid
assert found.dashboard_title == "Test UUID Dashboard"
# Find by numeric id (should still work)
found_by_id = DashboardDAO.find_by_id(dashboard.id, skip_base_filter=True)
assert found_by_id is not None
assert found_by_id.id == dashboard.id
# Test with non-existent uuid
not_found = DashboardDAO.find_by_id(str(uuid.uuid4()), skip_base_filter=True)
assert not_found is None
def test_find_by_id_with_slug_column(app_context: Session) -> None:
"""Test find_by_id with slug column fallback."""
# Create a dashboard with slug
dashboard = Dashboard(
dashboard_title="Test Slug Dashboard",
slug="test-slug-dashboard",
published=True,
)
db.session.add(dashboard)
db.session.commit()
# Find by slug using the slug column
found = DashboardDAO.find_by_id(
"test-slug-dashboard", id_column="slug", skip_base_filter=True
)
assert found is not None
assert found.slug == "test-slug-dashboard"
assert found.dashboard_title == "Test Slug Dashboard"
# Test with non-existent slug
not_found = DashboardDAO.find_by_id("non-existent-slug", skip_base_filter=True)
assert not_found is None
def test_find_by_id_with_invalid_column(app_context: Session) -> None:
"""Test find_by_id returns None when column doesn't exist."""
# This should return None gracefully
result = UserDAO.find_by_id("not_a_valid_id", skip_base_filter=True)
assert result is None
def test_find_by_id_skip_base_filter(app_context: Session) -> None:
"""Test find_by_id with skip_base_filter parameter."""
# Create users with different active states
active_user = User(
username="active_user",
first_name="Active",
last_name="User",
email="active@example.com",
active=True,
)
inactive_user = User(
username="inactive_user",
first_name="Inactive",
last_name="User",
email="inactive@example.com",
active=False,
)
db.session.add_all([active_user, inactive_user])
db.session.commit()
# Without skipping base filter (if one exists)
found_active = UserDAO.find_by_id(active_user.id, skip_base_filter=False)
assert found_active is not None
# With skipping base filter
found_active_skip = UserDAO.find_by_id(active_user.id, skip_base_filter=True)
assert found_active_skip is not None
# Both should find the user since UserDAO might not have a base filter
assert found_active.id == active_user.id
assert found_active_skip.id == active_user.id
def test_find_by_ids_with_default_column(app_context: Session) -> None:
"""Test find_by_ids with default 'id' column."""
# Create multiple users
users = []
for i in range(3):
user = User(
username=f"test_find_by_ids_{i}",
first_name=f"Test{i}",
last_name="User",
email=f"test{i}@example.com",
active=True,
)
users.append(user)
db.session.add(user)
db.session.commit()
# Find by multiple ids
ids = [user.id for user in users]
found = UserDAO.find_by_ids(ids, skip_base_filter=True)
assert len(found) == 3
found_ids = [u.id for u in found]
assert set(found_ids) == set(ids)
# Test with mix of existent and non-existent ids
mixed_ids = [users[0].id, 999999, users[1].id]
found_mixed = UserDAO.find_by_ids(mixed_ids, skip_base_filter=True)
assert len(found_mixed) == 2
# Test with empty list
found_empty = UserDAO.find_by_ids([], skip_base_filter=True)
assert found_empty == []
def test_find_by_ids_with_uuid_column(app_context: Session) -> None:
"""Test find_by_ids with uuid column."""
# Create multiple dashboards
dashboards = []
for i in range(3):
dashboard = Dashboard(
dashboard_title=f"Test UUID Dashboard {i}",
slug=f"test-uuid-dashboard-{i}",
published=True,
)
dashboards.append(dashboard)
db.session.add(dashboard)
db.session.commit()
# Find by multiple uuids
uuids = [str(dashboard.uuid) for dashboard in dashboards]
found = DashboardDAO.find_by_ids(uuids, id_column="uuid", skip_base_filter=True)
assert len(found) == 3
found_uuids = [str(d.uuid) for d in found]
assert set(found_uuids) == set(uuids)
# Test with mix of ids and uuids - search separately by column
found_by_id = DashboardDAO.find_by_ids([dashboards[0].id], skip_base_filter=True)
found_by_uuid = DashboardDAO.find_by_ids(
[str(dashboards[1].uuid)], id_column="uuid", skip_base_filter=True
)
assert len(found_by_id) == 1
assert len(found_by_uuid) == 1
def test_find_by_ids_with_slug_column(app_context: Session) -> None:
"""Test find_by_ids with slug column."""
# Create multiple dashboards
dashboards = []
for i in range(3):
dashboard = Dashboard(
dashboard_title=f"Test Slug Dashboard {i}",
slug=f"test-slug-dashboard-{i}",
published=True,
)
dashboards.append(dashboard)
db.session.add(dashboard)
db.session.commit()
# Find by multiple slugs
slugs = [dashboard.slug for dashboard in dashboards]
found = DashboardDAO.find_by_ids(slugs, id_column="slug", skip_base_filter=True)
assert len(found) == 3
found_slugs = [d.slug for d in found]
assert set(found_slugs) == set(slugs)
def test_find_by_ids_with_invalid_column(app_context: Session) -> None:
"""Test find_by_ids returns empty list when column doesn't exist."""
# This should return empty list gracefully
result = UserDAO.find_by_ids(["not_a_valid_id"], skip_base_filter=True)
assert result == []
def test_find_by_ids_skip_base_filter(app_context: Session) -> None:
"""Test find_by_ids with skip_base_filter parameter."""
# Create users
users = []
for i in range(3):
user = User(
username=f"test_skip_filter_{i}",
first_name=f"Test{i}",
last_name="User",
email=f"test{i}@example.com",
active=True,
)
users.append(user)
db.session.add(user)
db.session.commit()
ids = [user.id for user in users]
# Without skipping base filter
found_no_skip = UserDAO.find_by_ids(ids, skip_base_filter=False)
assert len(found_no_skip) == 3
# With skipping base filter
found_skip = UserDAO.find_by_ids(ids, skip_base_filter=True)
assert len(found_skip) == 3
def test_base_dao_create_with_item(app_context: Session) -> None:
"""Test BaseDAO.create with an item parameter."""
# Create a user item
user = User(
username="created_with_item",
first_name="Created",
last_name="Item",
email="created@example.com",
active=True,
)
# Create using the item
created = UserDAO.create(item=user)
assert created is not None
assert created.username == "created_with_item"
assert created.first_name == "Created"
# Verify it's in the session
assert created in db.session
# Commit and verify it persists
db.session.commit()
# Find it again to ensure it was saved
found = UserDAO.find_by_id(created.id, skip_base_filter=True)
assert found is not None
assert found.username == "created_with_item"
def test_base_dao_create_with_attributes(app_context: Session) -> None:
"""Test BaseDAO.create with attributes parameter."""
# Create using attributes dict
attributes = {
"username": "created_with_attrs",
"first_name": "Created",
"last_name": "Attrs",
"email": "attrs@example.com",
"active": True,
}
created = UserDAO.create(attributes=attributes)
assert created is not None
assert created.username == "created_with_attrs"
assert created.email == "attrs@example.com"
# Commit and verify
db.session.commit()
found = UserDAO.find_by_id(created.id, skip_base_filter=True)
assert found is not None
assert found.username == "created_with_attrs"
def test_base_dao_create_with_both_item_and_attributes(app_context: Session) -> None:
"""Test BaseDAO.create with both item and attributes (override behavior)."""
# Create a user item
user = User(
username="item_username",
first_name="Item",
last_name="User",
email="item@example.com",
active=False,
)
# Override some attributes
attributes = {
"username": "override_username",
"active": True,
}
created = UserDAO.create(item=user, attributes=attributes)
assert created is not None
assert created.username == "override_username" # Should be overridden
assert created.active is True # Should be overridden
assert created.first_name == "Item" # Should keep original
assert created.last_name == "User" # Should keep original
db.session.commit()
def test_base_dao_update_with_item(app_context: Session) -> None:
"""Test BaseDAO.update with an item parameter."""
# Create a user first
user = User(
username="update_test",
first_name="Original",
last_name="User",
email="original@example.com",
active=True,
)
db.session.add(user)
db.session.commit()
# Update the user
user.first_name = "Updated"
updated = UserDAO.update(item=user)
assert updated is not None
assert updated.first_name == "Updated"
db.session.commit()
# Verify the update persisted
found = UserDAO.find_by_id(user.id, skip_base_filter=True)
assert found is not None
assert found.first_name == "Updated"
def test_base_dao_update_with_attributes(app_context: Session) -> None:
"""Test BaseDAO.update with attributes parameter."""
# Create a user first
user = User(
username="update_attrs_test",
first_name="Original",
last_name="User",
email="original@example.com",
active=True,
)
db.session.add(user)
db.session.commit()
# Update using attributes
attributes = {"first_name": "Updated", "last_name": "Attr User"}
updated = UserDAO.update(item=user, attributes=attributes)
assert updated is not None
assert updated.first_name == "Updated"
assert updated.last_name == "Attr User"
db.session.commit()
def test_base_dao_update_detached_item(app_context: Session) -> None:
"""Test BaseDAO.update with a detached item."""
# Create a user first
user = User(
username="detached_test",
first_name="Original",
last_name="User",
email="detached@example.com",
active=True,
)
db.session.add(user)
db.session.commit()
user_id = user.id
# Expunge to detach from session
db.session.expunge(user)
# Update the detached user
user.first_name = "Updated Detached"
updated = UserDAO.update(item=user)
assert updated is not None
assert updated.first_name == "Updated Detached"
db.session.commit()
# Verify the update persisted
found = UserDAO.find_by_id(user_id, skip_base_filter=True)
assert found is not None
assert found.first_name == "Updated Detached"
def test_base_dao_delete_single_item(app_context: Session) -> None:
"""Test BaseDAO.delete with a single item."""
# Create a dashboard instead of user to avoid circular dependencies
dashboard = Dashboard(
dashboard_title="Delete Test",
slug="delete-test",
published=True,
)
db.session.add(dashboard)
db.session.commit()
dashboard_id = dashboard.id
DashboardDAO.delete([dashboard])
db.session.commit()
# Verify it's gone
found = DashboardDAO.find_by_id(dashboard_id, skip_base_filter=True)
assert found is None
def test_base_dao_delete_multiple_items(app_context: Session) -> None:
"""Test BaseDAO.delete with multiple items."""
# Create multiple dashboards instead of users to avoid circular dependencies
dashboards = []
for i in range(3):
dashboard = Dashboard(
dashboard_title=f"Delete Multi {i}",
slug=f"delete-multi-{i}",
published=True,
)
dashboards.append(dashboard)
db.session.add(dashboard)
db.session.commit()
dashboard_ids = [dashboard.id for dashboard in dashboards]
DashboardDAO.delete(dashboards)
db.session.commit()
# Verify they're all gone
for dashboard_id in dashboard_ids:
found = DashboardDAO.find_by_id(dashboard_id, skip_base_filter=True)
assert found is None
def test_base_dao_delete_empty_list(app_context: Session) -> None:
"""Test BaseDAO.delete with empty list."""
# Should not raise any errors
UserDAO.delete([])
db.session.commit()
# Just ensuring no exception is raised
def test_base_dao_find_all(app_context: Session) -> None:
"""Test BaseDAO.find_all method."""
# Create some users
users = []
for i in range(3):
user = User(
username=f"find_all_{i}",
first_name=f"Find{i}",
last_name="All",
email=f"findall{i}@example.com",
active=True,
)
users.append(user)
db.session.add(user)
db.session.commit()
# Find all users
all_users = UserDAO.find_all()
assert len(all_users) >= 3 # At least our 3 users
# Check our users are in the results
usernames = [u.username for u in all_users]
for user in users:
assert user.username in usernames
def test_base_dao_find_one_or_none(app_context: Session) -> None:
"""Test BaseDAO.find_one_or_none method."""
# Create users with specific criteria
user1 = User(
username="unique_username_123",
first_name="Unique",
last_name="User",
email="unique@example.com",
active=True,
)
user2 = User(
username="another_user",
first_name="Another",
last_name="User",
email="another@example.com",
active=True,
)
user3 = User(
username="third_user",
first_name="Another", # Same first name as user2
last_name="User",
email="third@example.com",
active=True,
)
db.session.add_all([user1, user2, user3])
db.session.commit()
# Find one with unique criteria
found = UserDAO.find_one_or_none(username="unique_username_123")
assert found is not None
assert found.username == "unique_username_123"
# Find none with non-existent criteria
not_found = UserDAO.find_one_or_none(username="non_existent_user")
assert not_found is None
db.session.commit()
def test_base_dao_list_returns_results(user_with_data: Session) -> None:
"""Test that BaseDAO.list returns results and total."""
results, total = UserDAO.list()
assert isinstance(results, list)
assert isinstance(total, int)
assert total >= 1 # At least the fixture user
def test_base_dao_list_with_column_operators(user_with_data: Session) -> None:
"""Test BaseDAO.list with column operators."""
column_operators = [
ColumnOperator(col="username", opr=ColumnOperatorEnum.eq, value="testuser")
]
results, total = UserDAO.list(column_operators=column_operators)
assert total == 1
assert results[0].username == "testuser"
def test_base_dao_list_with_non_matching_column_operator(
user_with_data: Session,
) -> None:
"""Test BaseDAO.list with non-matching column operator."""
column_operators = [
ColumnOperator(
col="username", opr=ColumnOperatorEnum.eq, value="nonexistentuser"
)
]
results, total = UserDAO.list(column_operators=column_operators)
assert total == 0
assert results == []
def test_base_dao_count_returns_value(user_with_data: Session) -> None:
"""Test that BaseDAO.count returns correct count."""
count = UserDAO.count()
assert isinstance(count, int)
assert count >= 1 # At least the fixture user
def test_base_dao_count_with_column_operators(user_with_data: Session) -> None:
"""Test BaseDAO.count with column operators."""
# Count with matching operator
column_operators = [
ColumnOperator(col="username", opr=ColumnOperatorEnum.eq, value="testuser")
]
count = UserDAO.count(column_operators=column_operators)
assert count == 1
# Count with non-matching operator
column_operators = [
ColumnOperator(
col="username", opr=ColumnOperatorEnum.eq, value="nonexistentuser"
)
]
count = UserDAO.count(column_operators=column_operators)
assert count == 0
def test_base_dao_list_ordering(user_with_data: Session) -> None:
"""Test BaseDAO.list with ordering."""
# Create additional users with predictable names
users = []
for i in range(3):
user = User(
# Let database auto-generate IDs to avoid conflicts
username=f"order_test_{i}",
first_name=f"Order{i}",
last_name="Test",
email=f"order{i}@example.com",
active=True,
)
users.append(user)
user_with_data.add(user)
user_with_data.commit()
# Test ascending order
results_asc, _ = UserDAO.list(
order_column="username", order_direction="asc", page_size=100
)
usernames_asc = [r.username for r in results_asc]
# Check that our test users are in order
assert usernames_asc.index("order_test_0") < usernames_asc.index("order_test_1")
assert usernames_asc.index("order_test_1") < usernames_asc.index("order_test_2")
# Test descending order
results_desc, _ = UserDAO.list(
order_column="username", order_direction="desc", page_size=100
)
usernames_desc = [r.username for r in results_desc]
# Check that our test users are in reverse order
assert usernames_desc.index("order_test_2") < usernames_desc.index("order_test_1")
assert usernames_desc.index("order_test_1") < usernames_desc.index("order_test_0")
for user in users:
user_with_data.delete(user)
user_with_data.commit()
def test_base_dao_list_paging(user_with_data: Session) -> None:
"""Test BaseDAO.list with paging."""
# Create additional users for paging
users = []
for i in range(10):
user = User(
username=f"page_test_{i}",
first_name=f"Page{i}",
last_name="Test",
email=f"page{i}@example.com",
active=True,
)
users.append(user)
user_with_data.add(user)
user_with_data.commit()
# Test first page
page1_results, page1_total = UserDAO.list(page=0, page_size=5, order_column="id")
assert len(page1_results) <= 5
assert page1_total >= 10 # At least our 10 users
# Test second page
page2_results, page2_total = UserDAO.list(page=1, page_size=5, order_column="id")
assert len(page2_results) <= 5
assert page2_total >= 10
# Results should be different
page1_ids = [r.id for r in page1_results]
page2_ids = [r.id for r in page2_results]
assert set(page1_ids).isdisjoint(set(page2_ids)) # No overlap
for user in users:
user_with_data.delete(user)
user_with_data.commit()
def test_base_dao_list_search(user_with_data: Session) -> None:
"""Test BaseDAO.list with search."""
# Create users with searchable names
users = []
for i in range(3):
user = User(
id=400 + i,
username=f"searchable_{i}",
first_name=f"Searchable{i}",
last_name="User",
email=f"search{i}@example.com",
active=True,
)
users.append(user)
user_with_data.add(user)
# Create some non-matching users
for i in range(2):
user = User(
id=410 + i,
username=f"other_{i}",
first_name=f"Other{i}",
last_name="Person",
email=f"other{i}@example.com",
active=True,
)
users.append(user)
user_with_data.add(user)
user_with_data.commit()
# Search for "searchable"
results, total = UserDAO.list(
search="searchable", search_columns=["username", "first_name"]
)
assert total >= 3 # At least our 3 searchable users
# Verify search functionality works - count how many of our test users are found
searchable_test_users = [
r
for r in results
if "searchable" in (r.username.lower() + " " + r.first_name.lower())
]
assert len(searchable_test_users) >= 3 # Our created test users should be found
# Verify the search actually filtered results (total should be reasonable)
assert total > 0 # Search returned some results
for user in users:
user_with_data.delete(user)
user_with_data.commit()
def test_base_dao_list_search_wildcard_injection(user_with_data: Session) -> None:
"""Verify that search='%' is treated literally and does not match all rows."""
users = []
for i in range(3):
user = User(
id=420 + i,
username=f"nowildcard_{i}",
first_name=f"NoWild{i}",
last_name="Card",
email=f"nowild{i}@example.com",
active=True,
)
users.append(user)
user_with_data.add(user)
user_with_data.commit()
# '%' must be escaped; it should not match any of our plain-name users
results, total = UserDAO.list(search="%", search_columns=["username", "first_name"])
result_usernames = {r.username for r in results}
for user in users:
assert user.username not in result_usernames, (
f"search='%' should not match '{user.username}' — LIKE wildcard injection"
)
for user in users:
user_with_data.delete(user)
user_with_data.commit()
def test_base_dao_list_column_operator_wildcard_injection(
user_with_data: Session,
) -> None:
"""Verify that column_operators with '%' values are treated literally."""
users = []
for i in range(3):
user = User(
id=430 + i,
username=f"opwildcard_{i}",
first_name=f"OpWild{i}",
last_name="Card",
email=f"opwild{i}@example.com",
active=True,
)
users.append(user)
user_with_data.add(user)
user_with_data.commit()
# Each wildcard operator with '%' as the value must not match plain-name rows
for opr in (
ColumnOperatorEnum.ct,
ColumnOperatorEnum.like,
ColumnOperatorEnum.ilike,
ColumnOperatorEnum.sw,
ColumnOperatorEnum.ew,
):
results, _ = UserDAO.list(
column_operators=[ColumnOperator(col="username", opr=opr, value="%")]
)
result_usernames = {r.username for r in results}
for user in users:
assert user.username not in result_usernames, (
f"opr={opr!r} with value='%' should not match '{user.username}'"
)
for user in users:
user_with_data.delete(user)
user_with_data.commit()
def test_base_dao_list_custom_filter(user_with_data: Session) -> None:
"""Test BaseDAO.list with custom filters."""
# Create users with specific attributes
active_user = User(
id=500,
username="active_custom",
first_name="Active",
last_name="Custom",
email="active@custom.com",
active=True,
)
inactive_user = User(
id=501,
username="inactive_custom",
first_name="Inactive",
last_name="Custom",
email="inactive@custom.com",
active=False,
)
user_with_data.add_all([active_user, inactive_user])
user_with_data.commit()
# Create a custom filter for active users only
class ActiveUsersFilter(BaseFilter):
def __init__(self):
self.column_name = "active"
self.datamodel = None
self.model = User # Set model directly
def apply(self, query, value):
return query.filter(User.active.is_(True))
custom_filters = {"active_only": ActiveUsersFilter()}
results, total = UserDAO.list(custom_filters=custom_filters)
# All results should be active users
for result in results:
assert result.active is True
def test_base_dao_list_base_filter(user_with_data: Session) -> None:
"""Test BaseDAO.list with base_filter."""
# Create a DAO with a base filter
class FilteredUserDAO(BaseDAO[User]):
model_cls = User
class ActiveFilter(BaseFilter):
def apply(self, query, value):
return query.filter(User.active.is_(True))
base_filter = ActiveFilter
# Create active and inactive users
active_user = User(
id=600,
username="active_base",
first_name="Active",
last_name="Base",
email="active@base.com",
active=True,
)
inactive_user = User(
id=601,
username="inactive_base",
first_name="Inactive",
last_name="Base",
email="inactive@base.com",
active=False,
)
user_with_data.add_all([active_user, inactive_user])
user_with_data.commit()
# List should only return active users when base filter is applied
results, total = FilteredUserDAO.list()
# All results should be active
for result in results:
assert result.active is True
user_with_data.delete(active_user)
user_with_data.delete(inactive_user)
user_with_data.commit()
def test_base_dao_list_edge_cases(user_with_data: Session) -> None:
"""Test BaseDAO.list with edge cases."""
# Test with invalid order column (should not raise)
results, total = UserDAO.list(order_column="invalid_column")
assert isinstance(results, list)
assert isinstance(total, int)
# Test with invalid order direction (should default to asc)
results, total = UserDAO.list(order_direction="invalid")
assert isinstance(results, list)
assert isinstance(total, int)
# Test with negative page (should default to 0)
results, total = UserDAO.list(page=-1, page_size=10)
assert isinstance(results, list)
assert isinstance(total, int)
# Test with zero page size (should use default)
results, total = UserDAO.list(page_size=0)
assert isinstance(results, list)
assert isinstance(total, int)
# Test with very large page number (should return empty)
results, total = UserDAO.list(page=99999, page_size=10)
assert results == []
assert isinstance(total, int)
# Test with both search and column operators
column_operators = [
ColumnOperator(col="username", opr=ColumnOperatorEnum.sw, value="test")
]
results, total = UserDAO.list(
search="user", search_columns=["username"], column_operators=column_operators