Skip to content

Commit a9ccbb7

Browse files
committed
fixed failing testcases, pylint
Signed-off-by: Veeresh K <[email protected]>
1 parent ca9ce8e commit a9ccbb7

File tree

10 files changed

+135
-105
lines changed

10 files changed

+135
-105
lines changed

mcpgateway/middleware/mcp_path_rewrite_middleware.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,10 @@ async def __call__(self, scope, receive, send):
7373
'/tools'
7474
"""
7575

76-
7776
# Only handle HTTP requests, HTTPS uses scope["type"] == "http" in ASGI
7877
if scope["type"] != "http":
7978
await self.application(scope, receive, send)
8079
return
81-
8280
scope.setdefault("headers", [])
8381

8482
# Call auth check first

mcpgateway/routers/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# pragma: no cover

mcpgateway/routers/oauth_router.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
# First-Party
2121
from mcpgateway.db import Gateway, get_db
22+
from mcpgateway.services.gateway_service import GatewayService
2223
from mcpgateway.services.oauth_manager import OAuthError, OAuthManager
2324
from mcpgateway.services.token_storage_service import TokenStorageService
2425

@@ -28,7 +29,7 @@
2829

2930

3031
@oauth_router.get("/authorize/{gateway_id}")
31-
async def initiate_oauth_flow(gateway_id: str, request: Request, db: Session = Depends(get_db)) -> RedirectResponse:
32+
async def initiate_oauth_flow(gateway_id: str, _request: Request, db: Session = Depends(get_db)) -> RedirectResponse:
3233
"""Initiates the OAuth 2.0 Authorization Code flow for a specified gateway.
3334
3435
This endpoint retrieves the OAuth configuration for the given gateway, validates that
@@ -37,7 +38,7 @@ async def initiate_oauth_flow(gateway_id: str, request: Request, db: Session = D
3738
3839
Args:
3940
gateway_id: The unique identifier of the gateway to authorize.
40-
request: The FastAPI request object.
41+
_request: The FastAPI request object.
4142
db: The database session dependency.
4243
4344
Returns:
@@ -80,8 +81,7 @@ async def initiate_oauth_flow(gateway_id: str, request: Request, db: Session = D
8081
async def oauth_callback(
8182
code: str = Query(..., description="Authorization code from OAuth provider"),
8283
state: str = Query(..., description="State parameter for CSRF protection"),
83-
# Remove the gateway_id parameter requirement
84-
request: Request = None,
84+
_request: Request = None,
8585
db: Session = Depends(get_db),
8686
) -> HTMLResponse:
8787
"""Handle the OAuth callback and complete the authorization process.
@@ -93,7 +93,7 @@ async def oauth_callback(
9393
Args:
9494
code (str): The authorization code returned by the OAuth provider.
9595
state (str): The state parameter for CSRF protection, which encodes the gateway ID.
96-
request (Request): The incoming HTTP request object.
96+
_request (Request): The incoming HTTP request object.
9797
db (Session): The database session dependency.
9898
9999
Returns:
@@ -349,14 +349,14 @@ async def get_oauth_status(gateway_id: str, db: Session = Depends(get_db)) -> di
349349
"redirect_uri": oauth_config.get("redirect_uri"),
350350
"message": "Gateway configured for Authorization Code flow",
351351
}
352-
else:
353-
return {
354-
"oauth_enabled": True,
355-
"grant_type": grant_type,
356-
"client_id": oauth_config.get("client_id"),
357-
"scopes": oauth_config.get("scopes", []),
358-
"message": f"Gateway configured for {grant_type} flow",
359-
}
352+
353+
return {
354+
"oauth_enabled": True,
355+
"grant_type": grant_type,
356+
"client_id": oauth_config.get("client_id"),
357+
"scopes": oauth_config.get("scopes", []),
358+
"message": f"Gateway configured for {grant_type} flow",
359+
}
360360

361361
except HTTPException:
362362
raise
@@ -380,9 +380,6 @@ async def fetch_tools_after_oauth(gateway_id: str, db: Session = Depends(get_db)
380380
HTTPException: If fetching tools fails
381381
"""
382382
try:
383-
# First-Party
384-
from mcpgateway.services.gateway_service import GatewayService
385-
386383
gateway_service = GatewayService()
387384
result = await gateway_service.fetch_tools_after_oauth(db, gateway_id)
388385
tools_count = len(result.get("tools", []))

mcpgateway/routers/reverse_proxy.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -150,13 +150,13 @@ def list_sessions(self) -> list[Dict[str, Any]]:
150150
@reverse_proxy_router.websocket("/ws")
151151
async def websocket_endpoint(
152152
websocket: WebSocket,
153-
db: Session = Depends(get_db),
153+
_db: Session = Depends(get_db),
154154
):
155155
"""WebSocket endpoint for reverse proxy connections.
156156
157157
Args:
158158
websocket: WebSocket connection.
159-
db: Database session.
159+
_db: Database session.
160160
"""
161161
await websocket.accept()
162162

@@ -230,13 +230,13 @@ async def websocket_endpoint(
230230

231231
@reverse_proxy_router.get("/sessions")
232232
async def list_sessions(
233-
request: Request,
233+
_request: Request,
234234
_: str | dict = Depends(require_auth),
235235
):
236236
"""List all active reverse proxy sessions.
237237
238238
Args:
239-
request: HTTP request.
239+
_request: HTTP request.
240240
_: Authenticated user info (used for auth check).
241241
242242
Returns:
@@ -248,14 +248,14 @@ async def list_sessions(
248248
@reverse_proxy_router.delete("/sessions/{session_id}")
249249
async def disconnect_session(
250250
session_id: str,
251-
request: Request,
251+
_request: Request,
252252
_: str | dict = Depends(require_auth),
253253
):
254254
"""Disconnect a reverse proxy session.
255255
256256
Args:
257257
session_id: Session ID to disconnect.
258-
request: HTTP request.
258+
_request: HTTP request.
259259
_: Authenticated user info (used for auth check).
260260
261261
Returns:
@@ -279,15 +279,15 @@ async def disconnect_session(
279279
async def send_request_to_session(
280280
session_id: str,
281281
mcp_request: Dict[str, Any],
282-
request: Request,
282+
_request: Request,
283283
_: str | dict = Depends(require_auth),
284284
):
285285
"""Send an MCP request to a reverse proxy session.
286286
287287
Args:
288288
session_id: Session ID to send request to.
289289
mcp_request: MCP request to send.
290-
request: HTTP request.
290+
_request: HTTP request.
291291
_: Authenticated user info (used for auth check).
292292
293293
Returns:

mcpgateway/routers/setup_routes.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
tag_router,
2626
tool_router,
2727
utility_router,
28-
version_router,
2928
well_known_router,
3029
)
3130

mcpgateway/routers/v1/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# pragma: no cover

mcpgateway/routers/well_known.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def validate_security_txt(content: str) -> Optional[str]:
7575

7676

7777
@well_known_router.get("/.well-known/{filename:path}", include_in_schema=False)
78-
async def get_well_known_file(filename: str, response: Response, request: Request):
78+
async def get_well_known_file(filename: str, _response: Response, _request: Request):
7979
"""
8080
Serve well-known URI files.
8181
@@ -86,8 +86,8 @@ async def get_well_known_file(filename: str, response: Response, request: Reques
8686
8787
Args:
8888
filename: The well-known filename requested
89-
response: FastAPI response object for headers
90-
request: FastAPI request object for logging
89+
_response: FastAPI response object for headers
90+
_request: FastAPI request object for logging
9191
9292
Returns:
9393
Plain text content of the requested file
@@ -110,7 +110,7 @@ async def get_well_known_file(filename: str, response: Response, request: Reques
110110
return PlainTextResponse(content=settings.well_known_robots_txt, media_type="text/plain; charset=utf-8", headers=headers)
111111

112112
# Handle security.txt
113-
elif filename == "security.txt":
113+
if filename == "security.txt":
114114
if not settings.well_known_security_txt_enabled:
115115
raise HTTPException(status_code=404, detail="security.txt not configured")
116116

@@ -121,7 +121,7 @@ async def get_well_known_file(filename: str, response: Response, request: Reques
121121
return PlainTextResponse(content=content, media_type="text/plain; charset=utf-8", headers=common_headers)
122122

123123
# Handle custom files
124-
elif filename in settings.custom_well_known_files:
124+
if filename in settings.custom_well_known_files:
125125
content = settings.custom_well_known_files[filename]
126126

127127
# Determine content type
@@ -131,22 +131,20 @@ async def get_well_known_file(filename: str, response: Response, request: Reques
131131

132132
return PlainTextResponse(content=content, media_type=content_type, headers=common_headers)
133133

134-
# File not found
135-
else:
136-
# Provide helpful error for known well-known URIs
137-
if filename in WELL_KNOWN_REGISTRY:
138-
raise HTTPException(status_code=404, detail=f"{filename} is not configured. This is a {WELL_KNOWN_REGISTRY[filename]['description']} file.")
139-
else:
140-
raise HTTPException(status_code=404, detail="Not found")
134+
# File not found - provide helpful error for known well-known URIs
135+
if filename in WELL_KNOWN_REGISTRY:
136+
raise HTTPException(status_code=404, detail=f"{filename} is not configured. This is a {WELL_KNOWN_REGISTRY[filename]['description']} file.")
137+
138+
raise HTTPException(status_code=404, detail="Not found")
141139

142140

143141
@well_known_router.get("/admin/well-known", response_model=dict)
144-
async def get_well_known_status(user: str = Depends(require_auth)):
142+
async def get_well_known_status(_user: str = Depends(require_auth)):
145143
"""
146144
Get status of well-known URI configuration.
147145
148146
Args:
149-
user: Authenticated user from dependency injection.
147+
_user: Authenticated user from dependency injection.
150148
151149
Returns:
152150
Dict containing well-known configuration status and available files.

mcpgateway/utils/url_utils.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ def get_protocol_from_request(request: Request) -> str:
2121
if forwarded:
2222
# may be a comma-separated list; take the first
2323
return forwarded.split(",")[0].strip()
24+
2425
return request.url.scheme
2526

2627

@@ -37,5 +38,6 @@ def update_url_protocol(request: Request) -> str:
3738
parsed = urlparse(str(request.base_url))
3839
proto = get_protocol_from_request(request)
3940
new_parsed = parsed._replace(scheme=proto)
41+
4042
# urlunparse keeps netloc and path intact
4143
return urlunparse(new_parsed).rstrip("/")

tests/conftest.py

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
# -*- coding: utf-8 -*-
2-
"""
3-
2+
"""Location: ./tests/conftest.py
43
Copyright 2025
54
SPDX-License-Identifier: Apache-2.0
65
Authors: Mihai Criveti
7-
86
"""
97

108
# Standard
@@ -36,7 +34,7 @@ def event_loop():
3634
@pytest.fixture(scope="session")
3735
def test_db_url():
3836
"""Return the URL for the test database."""
39-
return "sqlite:///./test.db"
37+
return "sqlite:///:memory:"
4038

4139

4240
@pytest.fixture(scope="session")
@@ -74,13 +72,46 @@ def test_settings():
7472

7573

7674
@pytest.fixture
77-
def app(test_settings):
78-
"""Create a FastAPI test application."""
79-
with patch("mcpgateway.config.get_settings", return_value=test_settings):
80-
# First-Party
81-
from mcpgateway.main import app
75+
def app():
76+
"""Create a FastAPI test application with proper database setup."""
77+
# Use the existing app_with_temp_db fixture logic which works correctly
78+
mp = MonkeyPatch()
79+
80+
# 1) create temp SQLite file
81+
fd, path = tempfile.mkstemp(suffix=".db")
82+
url = f"sqlite:///{path}"
83+
84+
# 2) patch settings
85+
from mcpgateway.config import settings
86+
mp.setattr(settings, "database_url", url, raising=False)
87+
88+
# First-Party
89+
import mcpgateway.db as db_mod
90+
91+
engine = create_engine(url, connect_args={"check_same_thread": False}, poolclass=StaticPool)
92+
TestSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
93+
mp.setattr(db_mod, "engine", engine, raising=False)
94+
mp.setattr(db_mod, "SessionLocal", TestSessionLocal, raising=False)
8295

83-
yield app
96+
# 4) patch the already‑imported main module **without reloading**
97+
import mcpgateway.main as main_mod
98+
mp.setattr(main_mod, "SessionLocal", TestSessionLocal, raising=False)
99+
# (patch engine too if your code references it)
100+
mp.setattr(main_mod, "engine", engine, raising=False)
101+
102+
# 4) create schema
103+
db_mod.Base.metadata.create_all(bind=engine)
104+
105+
# First-Party
106+
from mcpgateway.main import app
107+
108+
yield app
109+
110+
# 6) teardown
111+
mp.undo()
112+
engine.dispose()
113+
os.close(fd)
114+
os.unlink(path)
84115

85116

86117
@pytest.fixture
@@ -164,4 +195,4 @@ def app_with_temp_db():
164195
mp.undo()
165196
engine.dispose()
166197
os.close(fd)
167-
os.unlink(path)
198+
os.unlink(path)

0 commit comments

Comments
 (0)