fix(lint): auto-fix ruff violations and tune lint rules
Some checks failed
CI / ruff (push) Failing after 7s
CI / pytest (push) Failing after 1s
CI / architecture (push) Failing after 9s
CI / dependency-scanning (push) Successful in 27s
CI / audit (push) Successful in 8s
CI / docs (push) Has been skipped

- Auto-fixed 4,496 lint issues (import sorting, modern syntax, etc.)
- Added ignore rules for patterns intentional in this codebase:
  E402 (late imports), E712 (SQLAlchemy filters), B904 (raise from),
  SIM108/SIM105/SIM117 (readability preferences)
- Added per-file ignores for tests and scripts
- Excluded broken scripts/rename_terminology.py (has curly quotes)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-12 23:10:42 +01:00
parent e3428cc4aa
commit f20266167d
511 changed files with 5712 additions and 4682 deletions

View File

@@ -0,0 +1,317 @@
# app/modules/tenancy/tests/integration/test_merchant_auth_routes.py
"""
Integration tests for merchant authentication API routes.
Tests the merchant auth endpoints at:
/api/v1/merchants/auth/*
Uses real login flow (no dependency overrides) to verify JWT generation,
cookie setting, and token validation end-to-end.
"""
import uuid
import pytest
from app.modules.tenancy.models import Merchant, User
# ============================================================================
# Fixtures
# ============================================================================
BASE = "/api/v1/merchants/auth"
@pytest.fixture
def ma_owner(db):
"""Create a merchant owner user with known credentials."""
from middleware.auth import AuthManager
auth = AuthManager()
uid = uuid.uuid4().hex[:8]
user = User(
email=f"maowner_{uid}@test.com",
username=f"maowner_{uid}",
hashed_password=auth.hash_password("mapass123"),
role="store",
is_active=True,
)
db.add(user)
db.commit()
db.refresh(user)
return user
@pytest.fixture
def ma_merchant(db, ma_owner):
"""Create a merchant owned by ma_owner."""
merchant = Merchant(
name="Auth Test Merchant",
owner_user_id=ma_owner.id,
contact_email=ma_owner.email,
is_active=True,
is_verified=True,
)
db.add(merchant)
db.commit()
db.refresh(merchant)
return merchant
@pytest.fixture
def ma_non_merchant_user(db):
"""Create a user who does NOT own any merchants."""
from middleware.auth import AuthManager
auth = AuthManager()
uid = uuid.uuid4().hex[:8]
user = User(
email=f"nonmerch_{uid}@test.com",
username=f"nonmerch_{uid}",
hashed_password=auth.hash_password("nonmerch123"),
role="store",
is_active=True,
)
db.add(user)
db.commit()
db.refresh(user)
return user
@pytest.fixture
def ma_inactive_user(db):
"""Create an inactive user who owns a merchant."""
from middleware.auth import AuthManager
auth = AuthManager()
uid = uuid.uuid4().hex[:8]
user = User(
email=f"inactive_{uid}@test.com",
username=f"inactive_{uid}",
hashed_password=auth.hash_password("inactive123"),
role="store",
is_active=False,
)
db.add(user)
db.commit()
db.refresh(user)
merchant = Merchant(
name="Inactive Owner Merchant",
owner_user_id=user.id,
contact_email=user.email,
is_active=True,
is_verified=True,
)
db.add(merchant)
db.commit()
return user
# ============================================================================
# Login Tests
# ============================================================================
class TestMerchantLogin:
"""Tests for POST /api/v1/merchants/auth/login."""
def test_login_success(self, client, ma_owner, ma_merchant):
response = client.post(
f"{BASE}/login",
json={
"email_or_username": ma_owner.username,
"password": "mapass123",
},
)
assert response.status_code == 200
data = response.json()
assert "access_token" in data
assert data["token_type"] == "bearer"
assert "expires_in" in data
assert "user" in data
def test_login_sets_cookie(self, client, ma_owner, ma_merchant):
response = client.post(
f"{BASE}/login",
json={
"email_or_username": ma_owner.username,
"password": "mapass123",
},
)
assert response.status_code == 200
# Check Set-Cookie header
cookies = response.headers.get_list("set-cookie") if hasattr(response.headers, "get_list") else [
v for k, v in response.headers.items() if k.lower() == "set-cookie"
]
merchant_cookies = [c for c in cookies if "merchant_token" in c]
assert len(merchant_cookies) > 0
# Verify path restriction
assert "path=/merchants" in merchant_cookies[0].lower() or "Path=/merchants" in merchant_cookies[0]
def test_login_wrong_password(self, client, ma_owner, ma_merchant):
response = client.post(
f"{BASE}/login",
json={
"email_or_username": ma_owner.username,
"password": "wrong_password",
},
)
assert response.status_code == 401
def test_login_non_merchant_user(self, client, ma_non_merchant_user):
response = client.post(
f"{BASE}/login",
json={
"email_or_username": ma_non_merchant_user.username,
"password": "nonmerch123",
},
)
# Should fail because user doesn't own any merchants
assert response.status_code in (401, 403)
def test_login_inactive_user(self, client, ma_inactive_user):
response = client.post(
f"{BASE}/login",
json={
"email_or_username": ma_inactive_user.username,
"password": "inactive123",
},
)
assert response.status_code in (401, 403)
# ============================================================================
# Me Tests
# ============================================================================
class TestMerchantMe:
"""Tests for GET /api/v1/merchants/auth/me."""
def test_me_success(self, client, ma_owner, ma_merchant):
# Login first to get token
login_resp = client.post(
f"{BASE}/login",
json={
"email_or_username": ma_owner.username,
"password": "mapass123",
},
)
assert login_resp.status_code == 200
token = login_resp.json()["access_token"]
# Call /me with the token
response = client.get(
f"{BASE}/me",
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 200
data = response.json()
assert data["username"] == ma_owner.username
assert data["email"] == ma_owner.email
def test_me_no_token(self, client):
response = client.get(f"{BASE}/me")
assert response.status_code in (401, 403)
# ============================================================================
# Logout Tests
# ============================================================================
class TestMerchantLogout:
"""Tests for POST /api/v1/merchants/auth/logout."""
def test_logout_clears_cookie(self, client, ma_owner, ma_merchant):
# Login first
login_resp = client.post(
f"{BASE}/login",
json={
"email_or_username": ma_owner.username,
"password": "mapass123",
},
)
assert login_resp.status_code == 200
# Logout
response = client.post(f"{BASE}/logout")
assert response.status_code == 200
data = response.json()
assert "message" in data
# Check that cookie deletion is in response
cookies = [
v for k, v in response.headers.items() if k.lower() == "set-cookie"
]
merchant_cookies = [c for c in cookies if "merchant_token" in c]
assert len(merchant_cookies) > 0
# ============================================================================
# Auth Failure & Isolation Tests
# ============================================================================
class TestMerchantAuthFailures:
"""Tests for authentication edge cases and cross-portal isolation."""
def test_expired_token_rejected(self, client, ma_owner, ma_merchant):
"""An expired JWT should be rejected."""
from datetime import UTC, datetime, timedelta
from jose import jwt
# Create an already-expired token
payload = {
"sub": str(ma_owner.id),
"username": ma_owner.username,
"email": ma_owner.email,
"role": ma_owner.role,
"exp": datetime.now(UTC) - timedelta(hours=1),
"iat": datetime.now(UTC) - timedelta(hours=2),
}
import os
secret = os.getenv("JWT_SECRET_KEY", "your-secret-key-change-in-production-please")
expired_token = jwt.encode(payload, secret, algorithm="HS256")
response = client.get(
f"{BASE}/me",
headers={"Authorization": f"Bearer {expired_token}"},
)
assert response.status_code in (401, 403)
def test_invalid_token_rejected(self, client):
"""A completely invalid token should be rejected."""
response = client.get(
f"{BASE}/me",
headers={"Authorization": "Bearer invalid.token.here"},
)
assert response.status_code in (401, 403)
def test_store_token_not_accepted(self, client, db, ma_owner, ma_merchant):
"""A store-context token should not grant merchant /me access.
Store tokens include token_type=store which the merchant auth
dependency does not accept.
"""
from middleware.auth import AuthManager
auth = AuthManager()
# Create a real token for the user, but with store context
token_data = auth.create_access_token(
user=ma_owner,
store_id=999,
store_code="FAKE_STORE",
store_role="owner",
)
response = client.get(
f"{BASE}/me",
headers={"Authorization": f"Bearer {token_data['access_token']}"},
)
# Store tokens should be rejected at merchant endpoints
# (they have store context which merchant auth doesn't accept)
assert response.status_code in (401, 403)

View File

@@ -0,0 +1,233 @@
# app/modules/tenancy/tests/integration/test_merchant_routes.py
"""
Integration tests for merchant portal tenancy API routes.
Tests the merchant portal endpoints at:
/api/v1/merchants/account/*
Authentication: Overrides get_merchant_for_current_user and
get_current_merchant_api with mocks that return the test merchant/user.
"""
import uuid
import pytest
from app.api.deps import get_current_merchant_api, get_merchant_for_current_user
from app.modules.tenancy.models import Merchant, Store, User
from main import app
from models.schema.auth import UserContext
# ============================================================================
# Fixtures
# ============================================================================
BASE = "/api/v1/merchants/account"
@pytest.fixture
def mt_owner(db):
"""Create a merchant owner user."""
from middleware.auth import AuthManager
auth = AuthManager()
uid = uuid.uuid4().hex[:8]
user = User(
email=f"mtowner_{uid}@test.com",
username=f"mtowner_{uid}",
hashed_password=auth.hash_password("mtpass123"),
role="store",
is_active=True,
)
db.add(user)
db.commit()
db.refresh(user)
return user
@pytest.fixture
def mt_merchant(db, mt_owner):
"""Create a merchant owned by mt_owner."""
merchant = Merchant(
name="Merchant Portal Test",
description="A test merchant for portal routes",
owner_user_id=mt_owner.id,
contact_email=mt_owner.email,
contact_phone="+352 123 456",
website="https://example.com",
business_address="1 Rue Test, Luxembourg",
tax_number="LU12345678",
is_active=True,
is_verified=True,
)
db.add(merchant)
db.commit()
db.refresh(merchant)
return merchant
@pytest.fixture
def mt_stores(db, mt_merchant):
"""Create stores for the merchant."""
stores = []
for i in range(3):
uid = uuid.uuid4().hex[:8]
store = Store(
merchant_id=mt_merchant.id,
store_code=f"MT_{uid.upper()}",
subdomain=f"mtstore{uid}",
name=f"MT Store {i}",
is_active=i < 2, # Third store inactive
is_verified=True,
)
db.add(store)
stores.append(store)
db.commit()
for s in stores:
db.refresh(s)
return stores
@pytest.fixture
def mt_auth(mt_owner, mt_merchant):
"""Override auth dependencies to return the test merchant/user."""
user_context = UserContext(
id=mt_owner.id,
email=mt_owner.email,
username=mt_owner.username,
role="store",
is_active=True,
)
def _override_merchant():
return mt_merchant
def _override_user():
return user_context
app.dependency_overrides[get_merchant_for_current_user] = _override_merchant
app.dependency_overrides[get_current_merchant_api] = _override_user
yield {"Authorization": "Bearer fake-token"}
app.dependency_overrides.pop(get_merchant_for_current_user, None)
app.dependency_overrides.pop(get_current_merchant_api, None)
# ============================================================================
# Store Endpoints
# ============================================================================
class TestMerchantStoresList:
"""Tests for GET /api/v1/merchants/account/stores."""
def test_list_stores_success(self, client, mt_auth, mt_stores):
response = client.get(f"{BASE}/stores", headers=mt_auth)
assert response.status_code == 200
data = response.json()
assert "stores" in data
assert "total" in data
assert data["total"] == 3
def test_list_stores_response_shape(self, client, mt_auth, mt_stores):
response = client.get(f"{BASE}/stores", headers=mt_auth)
assert response.status_code == 200
store = response.json()["stores"][0]
assert "id" in store
assert "name" in store
assert "store_code" in store
assert "is_active" in store
assert "subdomain" in store
def test_list_stores_pagination(self, client, mt_auth, mt_stores):
response = client.get(
f"{BASE}/stores",
params={"skip": 0, "limit": 2},
headers=mt_auth,
)
assert response.status_code == 200
data = response.json()
assert len(data["stores"]) == 2
assert data["total"] == 3
assert data["skip"] == 0
assert data["limit"] == 2
def test_list_stores_empty(self, client, mt_auth, mt_merchant):
response = client.get(f"{BASE}/stores", headers=mt_auth)
assert response.status_code == 200
data = response.json()
assert data["stores"] == []
assert data["total"] == 0
# ============================================================================
# Profile Endpoints
# ============================================================================
class TestMerchantProfile:
"""Tests for GET/PUT /api/v1/merchants/account/profile."""
def test_get_profile_success(self, client, mt_auth, mt_merchant):
response = client.get(f"{BASE}/profile", headers=mt_auth)
assert response.status_code == 200
data = response.json()
assert data["id"] == mt_merchant.id
assert data["name"] == "Merchant Portal Test"
assert data["description"] == "A test merchant for portal routes"
assert data["contact_email"] == mt_merchant.contact_email
assert data["contact_phone"] == "+352 123 456"
assert data["website"] == "https://example.com"
assert data["business_address"] == "1 Rue Test, Luxembourg"
assert data["tax_number"] == "LU12345678"
assert data["is_verified"] is True
def test_get_profile_all_fields_present(self, client, mt_auth, mt_merchant):
response = client.get(f"{BASE}/profile", headers=mt_auth)
assert response.status_code == 200
data = response.json()
expected_fields = {
"id", "name", "description", "contact_email", "contact_phone",
"website", "business_address", "tax_number", "is_verified",
}
assert expected_fields.issubset(set(data.keys()))
def test_update_profile_partial(self, client, mt_auth, mt_merchant):
response = client.put(
f"{BASE}/profile",
json={"name": "Updated Merchant Name"},
headers=mt_auth,
)
assert response.status_code == 200
data = response.json()
assert data["name"] == "Updated Merchant Name"
# Other fields should remain unchanged
assert data["contact_phone"] == "+352 123 456"
def test_update_profile_email_validation(self, client, mt_auth, mt_merchant):
response = client.put(
f"{BASE}/profile",
json={"contact_email": "not-an-email"},
headers=mt_auth,
)
assert response.status_code == 422
def test_update_profile_cannot_set_admin_fields(self, client, mt_auth, mt_merchant):
"""Admin-only fields (is_active, is_verified) are not accepted."""
response = client.put(
f"{BASE}/profile",
json={"is_active": False, "is_verified": False},
headers=mt_auth,
)
# Should succeed but ignore unknown fields (Pydantic extra="ignore" by default)
assert response.status_code == 200
data = response.json()
# is_verified should remain True (not changed)
assert data["is_verified"] is True
def test_update_profile_name_too_short(self, client, mt_auth, mt_merchant):
response = client.put(
f"{BASE}/profile",
json={"name": "A"},
headers=mt_auth,
)
assert response.status_code == 422