File size: 3,138 Bytes
6a0ff33 | 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 | """
Tests for authentication: signup, login, /me.
"""
class TestSignup:
def test_signup_success(self, client):
resp = client.post("/api/auth/signup", json={
"username": "newuser",
"email": "new@example.com",
"password": "securepass",
})
assert resp.status_code == 201
data = resp.json()
assert "access_token" in data
assert data["token_type"] == "bearer"
def test_signup_duplicate_username(self, client):
payload = {
"username": "dupuser",
"email": "dup1@example.com",
"password": "pass123",
}
client.post("/api/auth/signup", json=payload)
# Try again with same username
resp = client.post("/api/auth/signup", json={
"username": "dupuser",
"email": "dup2@example.com",
"password": "pass123",
})
assert resp.status_code == 409
def test_signup_duplicate_email(self, client):
client.post("/api/auth/signup", json={
"username": "user1",
"email": "same@example.com",
"password": "pass123",
})
resp = client.post("/api/auth/signup", json={
"username": "user2",
"email": "same@example.com",
"password": "pass123",
})
assert resp.status_code == 409
class TestLogin:
def test_login_success(self, client):
client.post("/api/auth/signup", json={
"username": "loginuser",
"email": "login@example.com",
"password": "mypassword",
})
resp = client.post("/api/auth/login", json={
"username": "loginuser",
"password": "mypassword",
})
assert resp.status_code == 200
assert "access_token" in resp.json()
def test_login_wrong_password(self, client):
client.post("/api/auth/signup", json={
"username": "wrongpw",
"email": "wrongpw@example.com",
"password": "correctpass",
})
resp = client.post("/api/auth/login", json={
"username": "wrongpw",
"password": "wrongpassword",
})
assert resp.status_code == 401
def test_login_nonexistent_user(self, client):
resp = client.post("/api/auth/login", json={
"username": "ghost",
"password": "nope",
})
assert resp.status_code == 401
class TestMe:
def test_me_returns_user(self, client, auth_headers):
resp = client.get("/api/auth/me", headers=auth_headers)
assert resp.status_code == 200
data = resp.json()
assert data["username"] == "testuser"
assert data["email"] == "test@example.com"
assert "id" in data
def test_me_requires_auth(self, client):
resp = client.get("/api/auth/me")
assert resp.status_code in (401, 403)
def test_me_rejects_bad_token(self, client):
resp = client.get("/api/auth/me", headers={
"Authorization": "Bearer invalid.token.here"
})
assert resp.status_code == 401
|