Skip to content

Commit efd84b9

Browse files
committed
Improvements to unit tests for new diff scans
1 parent 0b4f02c commit efd84b9

File tree

5 files changed

+464
-4
lines changed

5 files changed

+464
-4
lines changed

socketdev/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from socketdev.core.api import API
22
from socketdev.dependencies import Dependencies
3+
from socketdev.diffscans import DiffScans
34
from socketdev.export import Export
45
from socketdev.fullscans import FullScans
56
from socketdev.historical import Historical
@@ -61,6 +62,7 @@ def __init__(self, token: str, timeout: int = 1200):
6162
self.utils = Utils()
6263
self.labels = Labels(self.api)
6364
self.licensemetadata = LicenseMetadata(self.api)
65+
self.diffscans = DiffScans(self.api)
6466

6567
@staticmethod
6668
def set_timeout(timeout: int):

socketdev/core/api.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,9 @@ def do_request(
5454
def format_headers(headers_dict):
5555
return "\n".join(f"{k}: {v}" for k, v in headers_dict.items())
5656

57+
start_time = time.time()
5758
try:
58-
start_time = time.time()
59+
5960
response = requests.request(
6061
method.upper(), url, headers=headers, data=payload, files=files, timeout=self.request_timeout
6162
)
@@ -103,14 +104,19 @@ def format_headers(headers_dict):
103104
log.error(f"Upstream server error{path_str}{headers_str}")
104105
raise APIBadGateway()
105106
if response.status_code >= 400:
107+
try:
108+
error_json = response.json()
109+
except Exception:
110+
error_json = None
111+
error_message = error_json.get("error", {}).get("message") if error_json else response.text
106112
error = (
107-
f"Bad Request: HTTP original_status_code:{response.status_code}{path_str}{headers_str}"
113+
f"Bad Request: HTTP original_status_code:{response.status_code}{path_str}{headers_str}\n"
114+
f"Error message: {error_message}"
108115
)
109116
log.error(error)
110-
raise APIFailure()
117+
raise APIFailure(error)
111118

112119
return response
113-
114120
except Timeout:
115121
request_duration = time.time() - start_time
116122
log.error(f"Request timed out after {request_duration:.2f} seconds")

socketdev/diffscans/__init__.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import json
2+
import logging
3+
from typing import Any, Dict, Optional, Union
4+
5+
log = logging.getLogger("socketdev")
6+
7+
class DiffScans:
8+
def __init__(self, api):
9+
self.api = api
10+
11+
def list(self, org_slug: str, params: Optional[Dict[str, Any]] = None) -> dict:
12+
"""List all diff scans for an organization."""
13+
path = f"orgs/{org_slug}/diff-scans"
14+
if params:
15+
import urllib.parse
16+
path += "?" + urllib.parse.urlencode(params)
17+
response = self.api.do_request(path=path, method="GET")
18+
if response.status_code == 200:
19+
return response.json()
20+
log.error(f"Error listing diff scans: {response.status_code}, message: {response.text}")
21+
return {}
22+
23+
def get(self, org_slug: str, diff_scan_id: str) -> dict:
24+
"""Fetch a diff scan by ID."""
25+
path = f"orgs/{org_slug}/diff-scans/{diff_scan_id}"
26+
response = self.api.do_request(path=path, method="GET")
27+
if response.status_code == 200:
28+
return response.json()
29+
log.error(f"Error fetching diff scan: {response.status_code}, message: {response.text}")
30+
return {}
31+
32+
def create_from_repo(self, org_slug: str, repo_slug: str, files: list, params: Optional[Dict[str, Any]] = None) -> dict:
33+
"""Create a diff scan from repo HEAD, uploading files as multipart form data."""
34+
import urllib.parse
35+
path = f"orgs/{org_slug}/diff-scans/from-repo/{repo_slug}"
36+
if params:
37+
path += "?" + urllib.parse.urlencode(params)
38+
response = self.api.do_request(path=path, method="POST", files=files)
39+
if response.status_code in (200, 201):
40+
return response.json()
41+
log.error(f"Error creating diff scan from repo: {response.status_code}, message: {response.text}")
42+
return {}
43+
44+
def create_from_ids(self, org_slug: str, params: Dict[str, Any]) -> dict:
45+
"""Create a diff scan from two full scan IDs using query params."""
46+
import urllib.parse
47+
path = f"orgs/{org_slug}/diff-scans/from-ids"
48+
if params:
49+
path += "?" + urllib.parse.urlencode(params)
50+
response = self.api.do_request(path=path, method="POST")
51+
if response.status_code in (200, 201):
52+
return response.json()
53+
log.error(f"Error creating diff scan from IDs: {response.status_code}, message: {response.text}")
54+
return {}
55+
56+
def gfm(self, org_slug: str, diff_scan_id: str) -> dict:
57+
"""Fetch GFM (GitHub Flavored Markdown) comments for a diff scan."""
58+
path = f"orgs/{org_slug}/diff-scans/{diff_scan_id}/gfm"
59+
response = self.api.do_request(path=path, method="GET")
60+
if response.status_code == 200:
61+
return response.json()
62+
log.error(f"Error fetching diff scan GFM: {response.status_code}, message: {response.text}")
63+
return {}
64+
65+
def delete(self, org_slug: str, diff_scan_id: str) -> bool:
66+
"""Delete a diff scan by ID."""
67+
path = f"orgs/{org_slug}/diff-scans/{diff_scan_id}"
68+
response = self.api.do_request(path=path, method="DELETE")
69+
if response.status_code == 200:
70+
if "status" in response.json() and response.json()["status"] == "ok":
71+
return True
72+
log.error(f"Error deleting diff scan: {response.status_code}, message: {response.text}")
73+
return False

0 commit comments

Comments
 (0)