93 lines
2.6 KiB
Python
93 lines
2.6 KiB
Python
import json
|
|
import pytest
|
|
from backend.app import create_app # Adjust import paths based on your folder structure
|
|
|
|
|
|
@pytest.fixture
|
|
def client():
|
|
app = create_app()
|
|
app.config["TESTING"] = True
|
|
|
|
# Optionally: use a test-specific MongoDB URI.
|
|
# app.config["MONGO_URI"] = "your_test_mongodb_connection_string"
|
|
|
|
with app.test_client() as client:
|
|
yield client
|
|
|
|
|
|
def test_register_and_login(client):
|
|
# Registration test.
|
|
reg_payload = {
|
|
"username": "test",
|
|
"email": "test@example.com",
|
|
"password": "1234"
|
|
}
|
|
response = client.post(
|
|
"/api/register",
|
|
data=json.dumps(reg_payload),
|
|
content_type="application/json"
|
|
)
|
|
assert response.status_code == 201
|
|
reg_data = json.loads(response.data)
|
|
assert "token" in reg_data
|
|
user_id = reg_data["user_id"]
|
|
|
|
# Login test.
|
|
login_payload = {
|
|
"username": "test",
|
|
"password": "1234"
|
|
}
|
|
response = client.post(
|
|
"/api/login",
|
|
data=json.dumps(login_payload),
|
|
content_type="application/json"
|
|
)
|
|
assert response.status_code == 200
|
|
login_data = json.loads(response.data)
|
|
assert "token" in login_data
|
|
assert user_id == login_data["user_id"]
|
|
|
|
|
|
def test_delete_account(client):
|
|
# Step 1: Register a new user
|
|
reg_payload = {
|
|
"username": "testuse",
|
|
"email": "testuse@example.com",
|
|
"password": "TestPassword123"
|
|
}
|
|
response = client.post(
|
|
"/api/register",
|
|
data=json.dumps(reg_payload),
|
|
content_type="application/json"
|
|
)
|
|
assert response.status_code == 201
|
|
reg_data = json.loads(response.data)
|
|
token = reg_data["token"]
|
|
user_id = reg_data["user_id"]
|
|
|
|
# Step 2: Optionally, login to verify credentials and obtain a fresh token
|
|
login_payload = {
|
|
"username": "testuse",
|
|
"password": "TestPassword123"
|
|
}
|
|
response = client.post(
|
|
"/api/login",
|
|
data=json.dumps(login_payload),
|
|
content_type="application/json"
|
|
)
|
|
assert response.status_code == 200
|
|
login_data = json.loads(response.data)
|
|
assert "token" in login_data
|
|
assert user_id == login_data["user_id"]
|
|
|
|
# Use the token from login (or registration) and add the "Bearer" prefix as expected.
|
|
headers = {"Authorization": f"Bearer {login_data['token']}"}
|
|
|
|
# Step 3: Call the delete_account endpoint using the DELETE method.
|
|
response = client.delete("/api/delete_account", headers=headers)
|
|
# Expecting a successful deletion, i.e. status code 200.
|
|
assert response.status_code == 200
|
|
delete_data = json.loads(response.data)
|
|
assert "deleted successfully" in delete_data["message"]
|
|
|