-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathtest_api.py
More file actions
233 lines (178 loc) · 8 KB
/
test_api.py
File metadata and controls
233 lines (178 loc) · 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
"""
Flask API integration tests using mocked email backends.
No real email account needed — all connections are mocked.
"""
import json
import pytest
from unittest.mock import MagicMock, patch
import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from app import app as flask_app
@pytest.fixture
def client(tmp_path):
flask_app.config["TESTING"] = True
flask_app.config["SECRET_KEY"] = "test-secret"
# Use a temp contacts file for each test
import app as app_module
app_module._contact_book.__init__(str(tmp_path / "contacts.json"))
with flask_app.test_client() as c:
yield c
@pytest.fixture
def authed_client(client):
"""Client with a pre-seeded IMAP session."""
import app as app_module
mock_conn = MagicMock()
mock_conn.get_imap.return_value = MagicMock()
with flask_app.test_request_context():
from flask import session
pass
with client.session_transaction() as sess:
sess["sid"] = "test-session-id"
app_module._connections["test-session-id"] = {
"type": "imap",
"conn": mock_conn,
"email": "[email protected]",
}
yield client
app_module._connections.pop("test-session-id", None)
# ── Auth status ───────────────────────────────────────────────────────────────
def test_auth_status_unauthenticated(client):
res = client.get("/api/auth/status")
data = json.loads(res.data)
assert data["ok"] is True
assert data["data"]["authenticated"] is False
def test_auth_status_authenticated(authed_client):
res = authed_client.get("/api/auth/status")
data = json.loads(res.data)
assert data["data"]["authenticated"] is True
assert data["data"]["email"] == "[email protected]"
# ── IMAP Login ────────────────────────────────────────────────────────────────
def test_imap_login_missing_fields(client):
res = client.post("/api/auth/imap",
data=json.dumps({"provider": "yahoo"}),
content_type="application/json")
data = json.loads(res.data)
assert data["ok"] is False
assert res.status_code == 400
@patch("app.imap_auth.validate_credentials", return_value=(True, ""))
@patch("app.imap_auth.IMAPConnection")
def test_imap_login_success(mock_conn_cls, mock_validate, client):
mock_conn_cls.return_value = MagicMock()
res = client.post("/api/auth/imap",
data=json.dumps({
"provider": "yahoo",
"email": "[email protected]",
"password": "app-password-here"
}),
content_type="application/json")
data = json.loads(res.data)
assert data["ok"] is True
assert data["data"]["email"] == "[email protected]"
@patch("app.imap_auth.validate_credentials", return_value=(False, "Authentication failed"))
def test_imap_login_bad_credentials(mock_validate, client):
res = client.post("/api/auth/imap",
data=json.dumps({
"provider": "yahoo",
"email": "[email protected]",
"password": "wrong"
}),
content_type="application/json")
assert res.status_code == 401
# ── Contacts CRUD ─────────────────────────────────────────────────────────────
def test_contacts_empty(client):
res = client.get("/api/contacts")
data = json.loads(res.data)
assert data["ok"] is True
assert data["data"] == []
def test_add_contact(client):
res = client.post("/api/contacts",
data=json.dumps({"name": "Alice", "email": "[email protected]"}),
content_type="application/json")
assert res.status_code == 201
data = json.loads(res.data)
assert data["data"]["name"] == "Alice"
def test_add_contact_missing_fields(client):
res = client.post("/api/contacts",
data=json.dumps({"name": "Alice"}),
content_type="application/json")
assert res.status_code == 400
def test_search_contacts(client):
client.post("/api/contacts",
data=json.dumps({"name": "Alice", "email": "[email protected]"}),
content_type="application/json")
res = client.get("/api/contacts?q=alice")
data = json.loads(res.data)
assert len(data["data"]) == 1
def test_delete_contact(client):
add_res = client.post("/api/contacts",
data=json.dumps({"name": "Alice", "email": "[email protected]"}),
content_type="application/json")
contact_id = json.loads(add_res.data)["data"]["id"]
del_res = client.delete(f"/api/contacts/{contact_id}")
assert json.loads(del_res.data)["ok"] is True
assert client.get("/api/contacts").json["data"] == []
def test_delete_nonexistent_contact(client):
res = client.delete("/api/contacts/does-not-exist")
assert res.status_code == 404
# ── Email endpoints require auth ──────────────────────────────────────────────
def test_emails_require_auth(client):
res = client.get("/api/emails")
assert res.status_code == 401
def test_send_email_requires_auth(client):
res = client.post("/api/emails",
data=json.dumps({"to": "[email protected]", "body": "hi"}),
content_type="application/json")
assert res.status_code == 401
# ── Email list (mocked IMAP) ──────────────────────────────────────────────────
@patch("app.reader.imap_list_inbox")
def test_list_emails(mock_list, authed_client):
mock_list.return_value = {
"emails": [
{"id": "1", "from": "Bob <[email protected]>", "subject": "Hello",
"date": "Mon, 1 Jan 2024", "unread": True, "snippet": ""}
],
"next_page_token": None
}
res = authed_client.get("/api/emails")
data = json.loads(res.data)
assert data["ok"] is True
assert len(data["data"]["emails"]) == 1
assert data["data"]["emails"][0]["subject"] == "Hello"
@patch("app.reader.imap_get_email")
def test_get_single_email(mock_get, authed_client):
mock_get.return_value = {
"id": "42", "from": "Bob <[email protected]>", "to": "[email protected]",
"subject": "Hi", "date": "now", "body": "Hello there", "unread": True
}
res = authed_client.get("/api/emails/42")
data = json.loads(res.data)
assert data["data"]["body"] == "Hello there"
@patch("app.sender.smtp_send")
def test_send_email(mock_send, authed_client):
res = authed_client.post("/api/emails",
data=json.dumps({"to": "[email protected]", "subject": "Hey", "body": "Hello Bob"}),
content_type="application/json")
assert json.loads(res.data)["ok"] is True
mock_send.assert_called_once()
def test_send_email_missing_to(authed_client):
res = authed_client.post("/api/emails",
data=json.dumps({"body": "Hello"}),
content_type="application/json")
assert res.status_code == 400
@patch("app.reader.imap_delete")
def test_delete_email(mock_del, authed_client):
res = authed_client.delete("/api/emails/42")
assert json.loads(res.data)["ok"] is True
mock_del.assert_called_once()
@patch("app.reader.imap_mark_read")
def test_mark_read(mock_mark, authed_client):
res = authed_client.patch("/api/emails/42/read")
assert json.loads(res.data)["ok"] is True
mock_mark.assert_called_once()
# ── Logout ────────────────────────────────────────────────────────────────────
def test_logout(authed_client):
res = authed_client.post("/api/auth/logout")
assert json.loads(res.data)["ok"] is True
# Should be unauthenticated after logout
status = authed_client.get("/api/auth/status")
assert json.loads(status.data)["data"]["authenticated"] is False