-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconftest.py
More file actions
650 lines (529 loc) · 18.8 KB
/
Copy pathconftest.py
File metadata and controls
650 lines (529 loc) · 18.8 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
import pytest
import os
from typing import Generator, cast
pytest_plugins = ["tests.frontend.fixtures"]
from sqlmodel import Session, select
from fastapi.testclient import TestClient
from dotenv import load_dotenv
from utils.core.db import (
clear_engine_cache,
get_connection_url,
get_engine,
tear_down_db,
set_up_db,
create_default_roles,
ensure_database_exists,
)
from utils.core.models import (
User,
Organization,
Role,
Account,
AccountEmail,
Invitation,
)
from utils.core.auth import (
get_password_hash,
create_access_token,
create_tracked_refresh_token,
)
load_dotenv()
os.environ.setdefault("STRIPE_SECRET_KEY", "sk_test_dummy")
os.environ.setdefault("STRIPE_WEBHOOK_SECRET", "whsec_test_dummy")
os.environ.setdefault("STRIPE_PRICE_ID", "price_test_dummy")
from main import app
from datetime import datetime, UTC, timedelta
from utils.core.rate_limit import clear_all_rate_limiters
@pytest.fixture(autouse=True)
def reset_rate_limiters() -> Generator[None, None, None]:
clear_all_rate_limiters()
yield
clear_all_rate_limiters()
# Define a custom exception for test setup errors
class SetupError(Exception):
"""Exception raised for errors in the test setup process."""
def __init__(self, message="An error occurred during test setup"):
self.message = message
super().__init__(self.message)
@pytest.fixture
def env_vars(monkeypatch):
load_dotenv()
# monkeypatch remaining env vars
with monkeypatch.context() as m:
# Get valid db user, password, host, and port from env
m.setenv("DB_HOST", os.getenv("DB_HOST", "127.0.0.1"))
m.setenv("DB_PORT", os.getenv("DB_PORT", "5432"))
m.setenv("DB_USER", os.getenv("DB_USER", "postgres"))
m.setenv("DB_PASSWORD", os.getenv("DB_PASSWORD", "postgres"))
m.setenv("SECRET_KEY", "testsecretkey-that-is-at-least-32-bytes-long")
m.setenv("HOST_NAME", "Test Organization")
m.setenv("DB_NAME", "webapp-test-db")
m.setenv("RESEND_API_KEY", "test")
m.setenv("EMAIL_FROM", "test@example.com")
m.setenv("BASE_URL", "http://localhost:8000")
m.setenv("STRIPE_SECRET_KEY", "sk_test_dummy")
m.setenv("STRIPE_WEBHOOK_SECRET", "whsec_test_dummy")
m.setenv("STRIPE_PRICE_ID", "price_test_dummy")
m.setenv("STRIPE_PLAN_NAME", "Pro")
m.setenv("STRIPE_TAX_ENABLED", "0")
m.setenv("CSRF_ENABLED", "0")
yield
@pytest.fixture
def engine(env_vars):
"""
Create a new SQLModel engine for the test database.
Use PostgreSQL for testing to match production environment.
"""
# Use PostgreSQL for testing to match production environment. get_engine()
# returns the same cached pool the app itself uses via get_session(), so
# TestClient requests and direct test queries share one pool instead of
# opening a second one for the same database.
ensure_database_exists(get_connection_url())
engine = get_engine()
set_up_db(drop=True)
yield engine
# Clean up after tests
tear_down_db()
clear_engine_cache()
@pytest.fixture
def session(engine) -> Generator[Session, None, None]:
"""
Provide a session for database operations in tests.
"""
with Session(engine) as session:
yield session
@pytest.fixture
def test_account(session: Session) -> Account:
"""
Creates a test account in the database.
"""
account = Account(
email="test@example.com", hashed_password=get_password_hash("Test123!@#")
)
session.add(account)
session.commit()
session.refresh(account)
return account
@pytest.fixture
def test_user(session: Session, test_account: Account) -> User:
"""
Creates a test user in the database linked to the test account.
"""
user = User(name="Test User", account_id=test_account.id)
session.add(user)
session.commit()
session.refresh(user)
# Also refresh the account to ensure the relationship is loaded
session.refresh(test_account)
return user
@pytest.fixture
def test_account_email(session: Session, test_account: Account) -> AccountEmail:
"""
Creates a primary AccountEmail for the test account.
"""
account_email = AccountEmail(
account_id=test_account.id,
email=test_account.email,
is_primary=True,
verified=True,
verified_at=datetime.now(UTC),
)
session.add(account_email)
session.commit()
session.refresh(account_email)
return account_email
@pytest.fixture
def unauth_client(session: Session) -> Generator[TestClient, None, None]:
"""
Provides a TestClient instance without authentication.
"""
client = TestClient(app, follow_redirects=False)
yield client
@pytest.fixture
def auth_client(
session: Session, test_account: Account, test_user: User
) -> Generator[TestClient, None, None]:
"""
Provides a TestClient instance with valid authentication tokens.
"""
client = TestClient(app, follow_redirects=False)
# Create and set valid tokens
access_token = create_access_token({"sub": test_account.email})
refresh_token = create_tracked_refresh_token(
test_account.id, test_account.email, session
)
session.commit()
client.cookies.set("access_token", access_token)
client.cookies.set("refresh_token", refresh_token)
yield client
@pytest.fixture
def test_organization(session: Session) -> Organization:
"""Create a test organization with default roles and permissions"""
organization = Organization(name="Test Organization")
session.add(organization)
session.flush()
if organization.id:
# Use the utility function to create default roles and assign permissions
# This function handles the commit internally
create_default_roles(session, organization.id, check_first=False)
else:
pytest.fail("Failed to get organization ID after flush")
return organization
@pytest.fixture
def org_owner(session: Session, test_organization: Organization) -> User:
"""Create a user who is the owner of the test organization"""
# Create account
account = Account(
email="owner@example.com", hashed_password=get_password_hash("Owner123!@#")
)
session.add(account)
session.commit()
session.refresh(account)
# Create user
user = User(name="Org Owner", account_id=account.id)
session.add(user)
# Find the Owner role for the test organization
owner_role = session.exec(
select(Role)
.where(Role.organization_id == test_organization.id)
.where(Role.name == "Owner")
).first()
if owner_role is None:
pytest.fail("Owner role not found for test organization")
# Assign user to owner role
user.roles.append(owner_role)
session.commit()
session.refresh(user)
return user
@pytest.fixture
def org_admin_user(session: Session, test_organization: Organization) -> User:
"""Create a user with Administrator role in the test organization"""
# Create account
account = Account(
email="admin@example.com", hashed_password=get_password_hash("Admin123!@#")
)
session.add(account)
session.commit()
session.refresh(account)
# Create user
user = User(name="Admin User", account_id=account.id)
session.add(user)
# Find the Admin role for the test organization (already created with permissions)
admin_role = session.exec(
select(Role)
.where(Role.organization_id == test_organization.id)
.where(Role.name == "Administrator")
).first()
if admin_role is None:
pytest.fail("Administrator role not found for test organization")
# Assign role to user
user.roles.append(admin_role)
session.commit()
session.refresh(user)
return user
@pytest.fixture
def org_member_user(session: Session, test_organization: Organization) -> User:
"""Create a user with basic Member role in the test organization"""
# Create account
account = Account(
email="member@example.com", hashed_password=get_password_hash("Member123!@#")
)
session.add(account)
session.commit()
session.refresh(account)
# Create user
user = User(name="Member User", account_id=account.id)
session.add(user)
# Find the Member role for the test organization (already created)
member_role = session.exec(
select(Role)
.where(Role.organization_id == test_organization.id)
.where(Role.name == "Member")
).first()
if member_role is None:
pytest.fail("Member role not found for test organization")
# Assign role to user
user.roles.append(member_role)
session.commit()
session.refresh(user)
return user
@pytest.fixture
def non_member_user(session: Session) -> User:
"""Create a user who is not a member of the test organization"""
# Create account
account = Account(
email="nonmember@example.com",
hashed_password=get_password_hash("NonMember123!@#"),
)
session.add(account)
session.commit()
# Create user
user = User(name="Non-Member User", account_id=account.id)
session.add(user)
session.commit()
session.refresh(user)
return user
@pytest.fixture
def auth_client_owner(
session: Session, org_owner: User
) -> Generator[TestClient, None, None]:
"""Provides a TestClient authenticated as the organization owner"""
client = TestClient(app, follow_redirects=False)
# Initialize tokens
access_token = ""
refresh_token = ""
# Create and set valid tokens
if org_owner.account:
access_token = create_access_token({"sub": org_owner.account.email})
refresh_token = create_tracked_refresh_token(
org_owner.account.id, org_owner.account.email, session
)
session.commit()
client.cookies.set("access_token", access_token)
client.cookies.set("refresh_token", refresh_token)
yield client
@pytest.fixture
def auth_client_admin(
session: Session, org_admin_user: User
) -> Generator[TestClient, None, None]:
"""Provides a TestClient authenticated as an organization administrator"""
client = TestClient(app, follow_redirects=False)
# Initialize tokens
access_token = ""
refresh_token = ""
# Create and set valid tokens
if org_admin_user.account:
access_token = create_access_token({"sub": org_admin_user.account.email})
refresh_token = create_tracked_refresh_token(
org_admin_user.account.id, org_admin_user.account.email, session
)
session.commit()
client.cookies.set("access_token", access_token)
client.cookies.set("refresh_token", refresh_token)
yield client
@pytest.fixture
def auth_client_member(
session: Session, org_member_user: User
) -> Generator[TestClient, None, None]:
"""Provides a TestClient authenticated as the organization member"""
client = TestClient(app, follow_redirects=False)
# Initialize tokens
access_token = ""
refresh_token = ""
# Create and set valid tokens
if org_member_user.account:
access_token = create_access_token({"sub": org_member_user.account.email})
refresh_token = create_tracked_refresh_token(
org_member_user.account.id, org_member_user.account.email, session
)
session.commit()
client.cookies.set("access_token", access_token)
client.cookies.set("refresh_token", refresh_token)
yield client
@pytest.fixture
def auth_client_non_member(
session: Session, non_member_user: User
) -> Generator[TestClient, None, None]:
"""Provides a TestClient authenticated as a non-member"""
client = TestClient(app, follow_redirects=False)
# Initialize tokens
access_token = ""
refresh_token = ""
# Create and set valid tokens
if non_member_user.account:
access_token = create_access_token({"sub": non_member_user.account.email})
refresh_token = create_tracked_refresh_token(
non_member_user.account.id, non_member_user.account.email, session
)
session.commit()
client.cookies.set("access_token", access_token)
client.cookies.set("refresh_token", refresh_token)
yield client
@pytest.fixture
def second_test_organization(session: Session) -> Organization:
"""Create a second test organization for multi-organization tests"""
organization = Organization(name="Second Test Organization")
session.add(organization)
session.commit()
return organization
def add_owner_to_organization(
session: Session, user: User, organization: Organization
) -> None:
"""Assign an Owner role on organization to user (for multi-org dashboard tests)."""
assert organization.id is not None
create_default_roles(session, organization.id, check_first=False)
owner_role = session.exec(
select(Role)
.where(Role.organization_id == organization.id)
.where(Role.name == "Owner")
).first()
if owner_role is None:
raise AssertionError(f"Owner role not found for organization {organization.id}")
user.roles.append(owner_role)
session.add(user)
session.commit()
# --- Invitation Fixtures ---
@pytest.fixture
def member_role(session: Session, test_organization: Organization) -> Role:
"""Returns the 'Member' role for the test_organization."""
member_role = session.exec(
select(Role)
.where(Role.organization_id == test_organization.id)
.where(Role.name == "Member")
).first()
if member_role is None:
pytest.fail(f"Member role not found for organization {test_organization.id}")
return member_role
@pytest.fixture
def test_invitation(
session: Session, test_organization: Organization, member_role: Role
) -> Invitation:
"""Creates a valid, active Invitation for invitee@example.com."""
# Assert IDs are not None to satisfy type checker
assert test_organization.id is not None
assert member_role.id is not None
invitation = Invitation(
organization_id=test_organization.id,
role_id=member_role.id,
invitee_email="invitee@example.com",
token="valid-test-token",
expires_at=datetime.now(UTC) + timedelta(days=7),
)
session.add(invitation)
session.commit()
session.refresh(invitation)
return invitation
@pytest.fixture
def expired_invitation(
session: Session, test_organization: Organization, member_role: Role
) -> Invitation:
"""Creates an Invitation with an expiration date in the past."""
# Assert IDs are not None to satisfy type checker
assert test_organization.id is not None
assert member_role.id is not None
invitation = Invitation(
organization_id=test_organization.id,
role_id=member_role.id,
invitee_email="expired-invitee@example.com",
token="expired-test-token",
expires_at=datetime.now(UTC) - timedelta(days=1),
)
session.add(invitation)
session.commit()
session.refresh(invitation)
return invitation
@pytest.fixture
def used_invitation(
session: Session,
test_organization: Organization,
member_role: Role,
non_member_user: User,
) -> Invitation:
"""Creates an Invitation that has already been used."""
# Assert IDs are not None to satisfy type checker
assert test_organization.id is not None
assert member_role.id is not None
assert non_member_user.id is not None
invitation = Invitation(
organization_id=test_organization.id,
role_id=member_role.id,
invitee_email="used-invitee@example.com",
token="used-test-token",
expires_at=datetime.now(UTC) + timedelta(days=7),
used=True,
accepted_at=datetime.now(UTC),
accepted_by_user_id=non_member_user.id,
)
session.add(invitation)
session.commit()
session.refresh(invitation)
return invitation
@pytest.fixture
def existing_invitee_account(session: Session) -> Account:
"""Creates an Account for invitee@example.com with a primary AccountEmail."""
account = Account(
email="invitee@example.com", hashed_password=get_password_hash("Invitee123!@#")
)
session.add(account)
session.flush()
account_email = AccountEmail(
account_id=account.id,
email="invitee@example.com",
is_primary=True,
verified=True,
verified_at=datetime.now(UTC),
)
session.add(account_email)
session.commit()
session.refresh(account)
return account
@pytest.fixture
def existing_invitee_user(session: Session, existing_invitee_account: Account) -> User:
"""Creates a User linked to existing_invitee_account."""
user = User(name="Invitee User", account_id=existing_invitee_account.id)
session.add(user)
session.commit()
session.refresh(user)
# Refresh account to load user relationship
session.refresh(existing_invitee_account)
return user
@pytest.fixture
def auth_client_invitee(
session: Session, existing_invitee_user: User
) -> Generator[TestClient, None, None]:
"""Provides a TestClient authenticated as the existing_invitee_user."""
client = TestClient(app, follow_redirects=False)
# Initialize tokens
access_token = ""
refresh_token = ""
# Create and set valid tokens
if existing_invitee_user.account:
access_token = create_access_token({"sub": existing_invitee_user.account.email})
refresh_token = create_tracked_refresh_token(
existing_invitee_user.account.id,
existing_invitee_user.account.email,
session,
)
session.commit()
client.cookies.set("access_token", access_token)
client.cookies.set("refresh_token", refresh_token)
yield client
# --- Email Mocking Fixtures ---
@pytest.fixture
def mock_email_response():
"""
Returns a mock Email response object
"""
# Use dictionary unpacking to handle the 'from' keyword
email_data = {
"id": "mock_resend_id",
"from": "test@example.com",
"to": ["recipient@example.com"],
"created_at": "2023-01-01T00:00:00Z",
"subject": "Mock Subject",
"html": "<p>Mock HTML</p>",
"text": "Mock Text",
"bcc": [],
"cc": [],
"reply_to": [],
"last_event": "delivered",
}
# Ensure resend is imported
import resend
return cast(resend.Email, email_data)
@pytest.fixture
def mock_resend_send(mock_email_response):
"""
Patches resend.Emails.send to return a mock response
"""
# Ensure patch and resend are imported
from unittest.mock import patch
with patch("resend.Emails.send", return_value=mock_email_response) as mock:
yield mock
# --- HTMX Test Helpers ---
def htmx_headers() -> dict:
"""Headers that simulate an HTMX request."""
return {"HX-Request": "true", "HX-Current-URL": "http://testserver/"}
def is_html_partial(response) -> bool:
"""True if response is a 200 HTML fragment (not a full page)."""
return response.status_code == 200 and "<!DOCTYPE html>" not in response.text