feat: scaffold Flask + React app with schema and JSON error handling
Claude-Session: https://claude.ai/code/session_01M9MLit5Ko3X4s7rzC5Kv7X
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
import os
|
||||
import unittest
|
||||
|
||||
import psycopg2
|
||||
|
||||
from app import app
|
||||
|
||||
HTTPS = "https://localhost" # the session cookie is Secure
|
||||
|
||||
|
||||
def db_execute(sql: str, params: tuple = ()) -> list[tuple]:
|
||||
conn = psycopg2.connect(os.environ["DATABASE_URL"])
|
||||
try:
|
||||
with conn, conn.cursor() as cur:
|
||||
cur.execute(sql, params)
|
||||
return cur.fetchall() if cur.description else []
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
class ApiTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
if not os.environ["DATABASE_URL"].endswith("/books_test"):
|
||||
raise RuntimeError("Refusing to truncate a database that is not books_test")
|
||||
db_execute("TRUNCATE users, sessions, books, notes RESTART IDENTITY CASCADE")
|
||||
self.client = app.test_client()
|
||||
|
||||
def call(self, method, path, json=None, client=None):
|
||||
kwargs = {"method": method, "base_url": HTTPS}
|
||||
if json is not None:
|
||||
kwargs["json"] = json
|
||||
elif method != "GET":
|
||||
kwargs["content_type"] = "application/json"
|
||||
return (client or self.client).open(path, **kwargs)
|
||||
|
||||
def register(self, username="alice", password="correct horse battery", client=None):
|
||||
response = self.call("POST", "/api/auth/register", {"username": username, "password": password}, client)
|
||||
self.assertEqual(response.status_code, 201, response.get_json())
|
||||
return response
|
||||
|
||||
def other_user(self, username="bob"):
|
||||
client = app.test_client()
|
||||
self.register(username, client=client)
|
||||
return client
|
||||
|
||||
def genre_id(self, name: str) -> int:
|
||||
return db_execute("SELECT id FROM genres WHERE name = %s", (name,))[0][0]
|
||||
|
||||
def create_book(self, client=None, **overrides) -> dict:
|
||||
payload = {
|
||||
"title": "Dune",
|
||||
"author": "Frank Herbert",
|
||||
"genre_id": self.genre_id("Science Fiction"),
|
||||
"total_pages": 412,
|
||||
} | overrides
|
||||
response = self.call("POST", "/api/books", payload, client)
|
||||
self.assertEqual(response.status_code, 201, response.get_json())
|
||||
return response.get_json()
|
||||
Reference in New Issue
Block a user