1
+import pytest
2
+from backend.app.models import User, UserRole, AuditLog, Company, FiscalYear, FiscalYearStatus
3
+from backend.app.api.auth import (
4
+ hash_password,
5
+ verify_password,
6
+ create_access_token,
7
+ verify_access_token,
8
+)
9
+from backend.app.services.audit import log_audit_event
10
+from backend.app.config import settings
11
+
12
+
13
+def test_password_hashing_and_verification():
14
+ raw_pass = "SecurePass123!"
15
+ hashed = hash_password(raw_pass)
16
+ assert hashed != raw_pass
17
+ assert verify_password(raw_pass, hashed) is True
18
+ assert verify_password("WrongPass", hashed) is False
19
+
20
+
21
+def test_jwt_token_generation_and_verification():
22
+ token = create_access_token({"sub": "test_user", "role": "ADMIN"})
23
+ verified = verify_access_token(token)
24
+ assert verified["username"] == "test_user"
25
+ assert verified["role"] == "ADMIN"
26
+
27
+
28
+def test_jwt_token_invalid_format_rejection():
29
+ with pytest.raises(Exception):
30
+ verify_access_token("invalid.token.string")
31
+
32
+
33
+def test_user_creation_and_auth_persistence(db_session):
34
+ hashed = hash_password("pass123")
35
+ user = User(username="audit_admin", hashed_password=hashed, role=UserRole.ADMIN, is_active=True)
36
+ db_session.add(user)
37
+ db_session.commit()
38
+
39
+ persisted = db_session.query(User).filter_by(username="audit_admin").first()
40
+ assert persisted is not None
41
+ assert persisted.role == UserRole.ADMIN
42
+ assert verify_password("pass123", persisted.hashed_password) is True
43
+
44
+
45
+def test_audit_logging_service(db_session):
46
+ user = User(username="auditor_test", hashed_password="hash", role=UserRole.AUDITOR)
47
+ db_session.add(user)
48
+ db_session.commit()
49
+
50
+ log = log_audit_event(
51
+ db_session,
52
+ user_id=user.id,
53
+ user_action="TEST_ACTION",
54
+ entity_affected="FiscalYear",
55
+ action_type="CREATE",
56
+ context_metadata={"year": 1402},
57
+ )
58
+
59
+ assert log.id is not None
60
+ assert log.user_action == "TEST_ACTION"
61
+ assert log.entity_affected == "FiscalYear"
62
+
63
+ persisted_log = db_session.query(AuditLog).filter_by(id=log.id).first()
64
+ assert persisted_log is not None
65
+ assert persisted_log.context_metadata == {"year": 1402}
66
+
67
+
68
+def test_login_api_endpoint(client, db_session):
69
+ user = User(username="login_user", hashed_password=hash_password("mysecret"), role=UserRole.AUDITOR)
70
+ db_session.add(user)
71
+ db_session.commit()
72
+
73
+ res = client.post("/api/v1/auth/login", json={"username": "login_user", "password": "mysecret"})
74
+ assert res.status_code == 200
75
+ data = res.json()
76
+ assert "access_token" in data
77
+ assert data["username"] == "login_user"
78
+ assert data["role"] == "AUDITOR"
79
+
80
+
81
+def test_login_api_endpoint_invalid_password(client, db_session):
82
+ user = User(username="login_user2", hashed_password=hash_password("correctpass"), role=UserRole.AUDITOR)
83
+ db_session.add(user)
84
+ db_session.commit()
85
+
86
+ res = client.post("/api/v1/auth/login", json={"username": "login_user2", "password": "wrongpass"})
87
+ assert res.status_code == 401
88
+
89
+
90
+def test_audit_logs_api_endpoint(client, db_session):
91
+ user = User(username="sys_admin", hashed_password="hash", role=UserRole.ADMIN)
92
+ db_session.add(user)
93
+ db_session.commit()
94
+
95
+ log_audit_event(
96
+ db_session,
97
+ user_id=user.id,
98
+ user_action="SYSTEM_INIT",
99
+ entity_affected="System",
100
+ action_type="INIT",
101
+ )
102
+
103
+ res = client.get("/api/v1/audit-logs")
104
+ assert res.status_code == 200
105
+ logs = res.json()
106
+ assert len(logs) >= 1
107
+ assert logs[0]["user_action"] == "SYSTEM_INIT"
108
+
109
+
110
+def test_role_based_access_control_rejection(client, db_session):
111
+ # Setup viewer token/user context
112
+ user = User(username="viewer_user", hashed_password=hash_password("pass"), role=UserRole.VIEWER)
113
+ db_session.add(user)
114
+ db_session.commit()
115
+
116
+ token = create_access_token({"sub": "viewer_user", "role": "VIEWER"})
117
+
118
+ # Attempt snapshot creation which requires ADMIN or AUDITOR role
119
+ comp = Company(code="RBAC1", name="RBAC Corp")
120
+ db_session.add(comp)
121
+ db_session.commit()
122
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
123
+ db_session.add(fy)
124
+ db_session.commit()
125
+
126
+ res = client.post(
127
+ f"/api/v1/snapshots?year_id={fy.id}",
128
+ headers={"Authorization": f"Bearer {token}"}
129
+ )
130
+ assert res.status_code == 403
131
+
132
+
133
+def test_reporting_api_audit_log_trigger(client, db_session):
134
+ comp = Company(code="AUDIT_REP", name="Audit Report Corp")
135
+ db_session.add(comp)
136
+ db_session.commit()
137
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
138
+ db_session.add(fy)
139
+ db_session.commit()
140
+
141
+ client.get(f"/api/v1/reporting/trial-balance?year_id={fy.id}")
142
+
143
+ audit_entry = (
144
+ db_session.query(AuditLog)
145
+ .filter(AuditLog.user_action.like("%Trial Balance%"))
146
+ .first()
147
+ )
148
+ assert audit_entry is not None
149
+
150
+
151
+def test_snapshot_creation_audit_log_trigger(client, db_session):
152
+ comp = Company(code="AUDIT_SNAP", name="Audit Snapshot Corp")
153
+ db_session.add(comp)
154
+ db_session.commit()
155
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
156
+ db_session.add(fy)
157
+ db_session.commit()
158
+
159
+ client.post(f"/api/v1/snapshots?year_id={fy.id}")
160
+
161
+ audit_entry = (
162
+ db_session.query(AuditLog)
163
+ .filter(AuditLog.entity_affected == "StatementSnapshot")
164
+ .first()
165
+ )
166
+ assert audit_entry is not None
167
+
168
+
169
+def test_environment_configuration_handling():
170
+ assert settings.PROJECT_NAME is not None
171
+ assert settings.VERSION is not None
172
+ assert settings.API_V1_STR == "/api/v1"
173
+
174
+
175
+def test_postgresql_dialect_compatibility():
176
+ pg_url = "postgresql://user:password@localhost:5432/financial_db"
177
+ assert pg_url.startswith("postgresql://")
178
+
179
+
180
+def test_current_user_me_endpoint(client):
181
+ res = client.get("/api/v1/auth/me")
182
+ assert res.status_code == 200
183
+ assert "username" in res.json()
184
+
185
+
186
+def test_user_active_status(db_session):
187
+ user = User(username="inactive_user", hashed_password="hash", role=UserRole.VIEWER, is_active=False)
188
+ db_session.add(user)
189
+ db_session.commit()
190
+
191
+ persisted = db_session.query(User).filter_by(username="inactive_user").first()
192
+ assert persisted.is_active is False