-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.py
More file actions
150 lines (121 loc) · 4.83 KB
/
tests.py
File metadata and controls
150 lines (121 loc) · 4.83 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
"""
Backend tests for graphnote.
Uses SQLite + StaticPool - no Postgres or Docker required.
Run:
python -m pytest tests.py -v
python tests.py
"""
import sys
import os
import unittest
# Patch postgresql.JSONB -> generic JSON so SQLite works in-process
import sqlalchemy.dialects.postgresql as _pg_dialect
from sqlalchemy import JSON as _JSON
_pg_dialect.JSONB = _JSON
# Make the backend package importable from the project root
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "backend"))
# Set required env-vars BEFORE importing app.py
os.environ.setdefault("JWT_SECRET_KEY", "test-only-secret-key")
os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
from app import app as flask_app
from models import db, User, Graph, Comment, Like, News
from sqlalchemy.pool import StaticPool
from flask_jwt_extended import create_access_token
flask_app.config.update(
TESTING=True,
SQLALCHEMY_DATABASE_URI="sqlite:///:memory:",
SQLALCHEMY_ENGINE_OPTIONS={
"connect_args": {"check_same_thread": False},
"poolclass": StaticPool,
},
JWT_SECRET_KEY="test-only-secret-key",
JWT_TOKEN_LOCATION=["headers", "cookies"],
JWT_HEADER_NAME="Authorization",
JWT_HEADER_TYPE="Bearer",
JWT_COOKIE_CSRF_PROTECT=False,
)
def auth_header(user_id: int) -> dict:
with flask_app.app_context():
token = create_access_token(identity=str(user_id))
return {"Authorization": f"Bearer {token}"}
class TestBasicFlows(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.client = flask_app.test_client()
with flask_app.app_context():
db.drop_all()
db.create_all()
user = User(username="testuser")
user.set_password("password123")
db.session.add(user)
db.session.commit()
cls.user_id = user.id
graph = Graph(name="Test Graph", user_id=user.id, is_public=True, featured=False)
graph.nodes = []
db.session.add(graph)
db.session.commit()
cls.graph_id = graph.id
db.session.add(Comment(graph_id=graph.id, user_id=user.id, content="Hello"))
db.session.add(News(title="v1", content="First release"))
db.session.commit()
@classmethod
def tearDownClass(cls):
with flask_app.app_context():
db.drop_all()
# 1. Sign up a new account
def test_01_signup(self):
r = self.client.post("/auth/signup", json={"username": "newuser", "password": "newpass1"})
self.assertEqual(r.status_code, 201)
self.assertEqual(r.get_json()["username"], "newuser")
# 2. Login with valid credentials
def test_02_login(self):
r = self.client.post("/auth/login", json={"username": "testuser", "password": "password123"})
self.assertEqual(r.status_code, 200)
self.assertIn("user_id", r.get_json())
# 3. Login fails with wrong password
def test_03_login_wrong_password(self):
r = self.client.post("/auth/login", json={"username": "testuser", "password": "wrongpass"})
self.assertEqual(r.status_code, 401)
# 4. Logout
def test_04_logout(self):
r = self.client.post("/auth/logout")
self.assertEqual(r.status_code, 200)
# 5. Get public graph listing
def test_05_get_all_graphs(self):
r = self.client.get("/api/graphs")
self.assertEqual(r.status_code, 200)
ids = [g["id"] for g in r.get_json()]
self.assertIn(self.graph_id, ids)
# 6. Get a specific public graph
def test_06_get_graph_by_id(self):
r = self.client.get(f"/api/graph/{self.graph_id}")
self.assertEqual(r.status_code, 200)
self.assertEqual(r.get_json()["id"], self.graph_id)
# 7. Create a new graph while logged in
def test_07_create_graph(self):
r = self.client.post(
"/api/graphs",
json={"name": "My Graph", "nodes": []},
headers=auth_header(self.user_id),
)
self.assertEqual(r.status_code, 201)
self.assertEqual(r.get_json()["name"], "My Graph")
# 8. Get user profile
def test_08_get_user(self):
r = self.client.get(f"/api/user/{self.user_id}")
self.assertEqual(r.status_code, 200)
self.assertEqual(r.get_json()["username"], "testuser")
# 9. Like a graph and check the count increases
def test_09_like_graph(self):
r = self.client.post(f"/api/graph/{self.graph_id}/like", headers=auth_header(self.user_id))
self.assertEqual(r.status_code, 200)
data = r.get_json()
self.assertIn("liked", data)
self.assertIn("count", data)
# 10. Get news feed
def test_10_get_news(self):
r = self.client.get("/api/news")
self.assertEqual(r.status_code, 200)
self.assertGreater(len(r.get_json()), 0)
if __name__ == "__main__":
unittest.main(verbosity=2)