forked from 0xWheatyz/SPARC
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fc942b2aa4 |
@@ -1,263 +0,0 @@
|
|||||||
"""Tests for S3/MinIO storage backend in storage.py.
|
|
||||||
|
|
||||||
Covers issue #1660:
|
|
||||||
- S3StorageBackend read, write, exists, path_for
|
|
||||||
- Error handling: NoSuchKey, generic S3 errors, bucket auto-creation
|
|
||||||
- get_storage_backend() factory function
|
|
||||||
- LocalStorageBackend (basic sanity checks)
|
|
||||||
"""
|
|
||||||
|
|
||||||
from unittest.mock import MagicMock, patch
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from SPARC.storage import LocalStorageBackend, S3StorageBackend, get_storage_backend
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- S3StorageBackend ----------
|
|
||||||
|
|
||||||
class TestS3StorageBackend:
|
|
||||||
"""Tests for the S3-compatible storage backend."""
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def s3_backend(self):
|
|
||||||
"""Create an S3StorageBackend with a fully mocked boto3 client."""
|
|
||||||
with patch.dict("sys.modules", {"boto3": MagicMock()}):
|
|
||||||
import boto3 as mock_boto
|
|
||||||
mock_s3 = MagicMock()
|
|
||||||
mock_boto.client.return_value = mock_s3
|
|
||||||
mock_s3.head_bucket.return_value = {}
|
|
||||||
|
|
||||||
backend = S3StorageBackend(
|
|
||||||
bucket="test-bucket",
|
|
||||||
endpoint_url="http://minio:9000",
|
|
||||||
access_key="minioadmin",
|
|
||||||
secret_key="minioadmin",
|
|
||||||
)
|
|
||||||
# Expose mock for assertions
|
|
||||||
backend._mock_s3 = mock_s3
|
|
||||||
yield backend
|
|
||||||
|
|
||||||
def test_write_puts_object(self, s3_backend):
|
|
||||||
"""write() calls put_object with correct bucket, key, and body."""
|
|
||||||
s3_backend.write("US-12345678-B2.pdf", b"PDF content here")
|
|
||||||
|
|
||||||
s3_backend._mock_s3.put_object.assert_called_once_with(
|
|
||||||
Bucket="test-bucket",
|
|
||||||
Key="US-12345678-B2.pdf",
|
|
||||||
Body=b"PDF content here",
|
|
||||||
ContentType="application/pdf",
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_read_returns_body(self, s3_backend):
|
|
||||||
"""read() returns the Body content from get_object."""
|
|
||||||
mock_body = MagicMock()
|
|
||||||
mock_body.read.return_value = b"PDF data"
|
|
||||||
s3_backend._mock_s3.get_object.return_value = {"Body": mock_body}
|
|
||||||
|
|
||||||
result = s3_backend.read("US-12345678-B2.pdf")
|
|
||||||
|
|
||||||
assert result == b"PDF data"
|
|
||||||
s3_backend._mock_s3.get_object.assert_called_once_with(
|
|
||||||
Bucket="test-bucket",
|
|
||||||
Key="US-12345678-B2.pdf",
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_read_nosuchkey_raises_file_not_found(self, s3_backend):
|
|
||||||
"""read() raises FileNotFoundError when object does not exist."""
|
|
||||||
# Create a NoSuchKey exception class on the mock
|
|
||||||
nosuchkey = type("NoSuchKey", (Exception,), {})
|
|
||||||
s3_backend._mock_s3.exceptions.NoSuchKey = nosuchkey
|
|
||||||
s3_backend._mock_s3.get_object.side_effect = nosuchkey("not found")
|
|
||||||
|
|
||||||
# Reassign s3 to trigger the except branch
|
|
||||||
s3_backend.s3 = s3_backend._mock_s3
|
|
||||||
|
|
||||||
with pytest.raises(FileNotFoundError, match="S3 object not found"):
|
|
||||||
s3_backend.read("missing.pdf")
|
|
||||||
|
|
||||||
def test_read_generic_404_raises_file_not_found(self, s3_backend):
|
|
||||||
"""read() handles generic 404 errors from S3-compatible APIs."""
|
|
||||||
nosuchkey = type("NoSuchKey", (Exception,), {})
|
|
||||||
s3_backend._mock_s3.exceptions.NoSuchKey = nosuchkey
|
|
||||||
s3_backend.s3 = s3_backend._mock_s3
|
|
||||||
s3_backend.s3.get_object.side_effect = Exception("An error occurred (404)")
|
|
||||||
|
|
||||||
with pytest.raises(FileNotFoundError, match="S3 object not found"):
|
|
||||||
s3_backend.read("missing.pdf")
|
|
||||||
|
|
||||||
def test_read_other_error_re_raises(self, s3_backend):
|
|
||||||
"""read() re-raises non-404 errors."""
|
|
||||||
nosuchkey = type("NoSuchKey", (Exception,), {})
|
|
||||||
s3_backend._mock_s3.exceptions.NoSuchKey = nosuchkey
|
|
||||||
s3_backend.s3 = s3_backend._mock_s3
|
|
||||||
s3_backend.s3.get_object.side_effect = Exception("Internal server error")
|
|
||||||
|
|
||||||
with pytest.raises(Exception, match="Internal server error"):
|
|
||||||
s3_backend.read("some-file.pdf")
|
|
||||||
|
|
||||||
def test_exists_returns_true_for_existing_object(self, s3_backend):
|
|
||||||
"""exists() returns True when head_object succeeds with content."""
|
|
||||||
s3_backend._mock_s3.head_object.return_value = {"ContentLength": 1024}
|
|
||||||
|
|
||||||
assert s3_backend.exists("US-12345678-B2.pdf") is True
|
|
||||||
|
|
||||||
def test_exists_returns_false_for_missing_object(self, s3_backend):
|
|
||||||
"""exists() returns False when head_object raises an exception."""
|
|
||||||
s3_backend._mock_s3.head_object.side_effect = Exception("Not Found")
|
|
||||||
|
|
||||||
assert s3_backend.exists("missing.pdf") is False
|
|
||||||
|
|
||||||
def test_exists_returns_false_for_zero_length(self, s3_backend):
|
|
||||||
"""exists() returns False when object has zero content length."""
|
|
||||||
s3_backend._mock_s3.head_object.return_value = {"ContentLength": 0}
|
|
||||||
|
|
||||||
assert s3_backend.exists("empty.pdf") is False
|
|
||||||
|
|
||||||
def test_path_for_returns_s3_uri(self, s3_backend):
|
|
||||||
"""path_for() returns an s3:// URI."""
|
|
||||||
path = s3_backend.path_for("US-12345678-B2.pdf")
|
|
||||||
|
|
||||||
assert path == "s3://test-bucket/US-12345678-B2.pdf"
|
|
||||||
|
|
||||||
def test_constructor_creates_bucket_if_missing(self):
|
|
||||||
"""Constructor creates the bucket if head_bucket fails."""
|
|
||||||
with patch.dict("sys.modules", {"boto3": MagicMock()}):
|
|
||||||
import boto3 as mock_boto
|
|
||||||
mock_s3 = MagicMock()
|
|
||||||
mock_boto.client.return_value = mock_s3
|
|
||||||
mock_s3.head_bucket.side_effect = Exception("Bucket not found")
|
|
||||||
|
|
||||||
S3StorageBackend(
|
|
||||||
bucket="new-bucket",
|
|
||||||
endpoint_url="http://minio:9000",
|
|
||||||
access_key="admin",
|
|
||||||
secret_key="admin",
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_s3.create_bucket.assert_called_once_with(Bucket="new-bucket")
|
|
||||||
|
|
||||||
def test_constructor_handles_bucket_creation_failure(self):
|
|
||||||
"""Constructor logs warning but does not crash if bucket creation fails."""
|
|
||||||
with patch.dict("sys.modules", {"boto3": MagicMock()}):
|
|
||||||
import boto3 as mock_boto
|
|
||||||
mock_s3 = MagicMock()
|
|
||||||
mock_boto.client.return_value = mock_s3
|
|
||||||
mock_s3.head_bucket.side_effect = Exception("Bucket not found")
|
|
||||||
mock_s3.create_bucket.side_effect = Exception("Permission denied")
|
|
||||||
|
|
||||||
# Should not raise
|
|
||||||
backend = S3StorageBackend(
|
|
||||||
bucket="locked-bucket",
|
|
||||||
endpoint_url="http://minio:9000",
|
|
||||||
access_key="admin",
|
|
||||||
secret_key="admin",
|
|
||||||
)
|
|
||||||
assert backend.bucket == "locked-bucket"
|
|
||||||
|
|
||||||
def test_constructor_passes_endpoint_and_credentials(self):
|
|
||||||
"""Constructor passes endpoint_url and credentials to boto3.client."""
|
|
||||||
with patch.dict("sys.modules", {"boto3": MagicMock()}):
|
|
||||||
import boto3 as mock_boto
|
|
||||||
mock_s3 = MagicMock()
|
|
||||||
mock_boto.client.return_value = mock_s3
|
|
||||||
|
|
||||||
S3StorageBackend(
|
|
||||||
bucket="test",
|
|
||||||
endpoint_url="http://minio:9000",
|
|
||||||
access_key="mykey",
|
|
||||||
secret_key="mysecret",
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_boto.client.assert_called_with(
|
|
||||||
"s3",
|
|
||||||
endpoint_url="http://minio:9000",
|
|
||||||
aws_access_key_id="mykey",
|
|
||||||
aws_secret_access_key="mysecret",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- LocalStorageBackend ----------
|
|
||||||
|
|
||||||
class TestLocalStorageBackend:
|
|
||||||
"""Basic sanity checks for the local filesystem backend."""
|
|
||||||
|
|
||||||
def test_write_and_read(self, tmp_path):
|
|
||||||
"""Write and read round-trip produces identical content."""
|
|
||||||
backend = LocalStorageBackend(base_dir=str(tmp_path))
|
|
||||||
backend.write("test.pdf", b"hello world")
|
|
||||||
|
|
||||||
result = backend.read("test.pdf")
|
|
||||||
assert result == b"hello world"
|
|
||||||
|
|
||||||
def test_read_missing_file_raises(self, tmp_path):
|
|
||||||
"""Reading a non-existent file raises FileNotFoundError."""
|
|
||||||
backend = LocalStorageBackend(base_dir=str(tmp_path))
|
|
||||||
|
|
||||||
with pytest.raises(FileNotFoundError):
|
|
||||||
backend.read("nonexistent.pdf")
|
|
||||||
|
|
||||||
def test_exists_true_for_written_file(self, tmp_path):
|
|
||||||
"""exists() returns True after writing a file."""
|
|
||||||
backend = LocalStorageBackend(base_dir=str(tmp_path))
|
|
||||||
backend.write("test.pdf", b"data")
|
|
||||||
|
|
||||||
assert backend.exists("test.pdf") is True
|
|
||||||
|
|
||||||
def test_exists_false_for_missing_file(self, tmp_path):
|
|
||||||
"""exists() returns False for non-existent file."""
|
|
||||||
backend = LocalStorageBackend(base_dir=str(tmp_path))
|
|
||||||
|
|
||||||
assert backend.exists("missing.pdf") is False
|
|
||||||
|
|
||||||
def test_exists_false_for_empty_file(self, tmp_path):
|
|
||||||
"""exists() returns False for zero-length file."""
|
|
||||||
backend = LocalStorageBackend(base_dir=str(tmp_path))
|
|
||||||
backend.write("empty.pdf", b"")
|
|
||||||
|
|
||||||
assert backend.exists("empty.pdf") is False
|
|
||||||
|
|
||||||
def test_path_for_returns_full_path(self, tmp_path):
|
|
||||||
"""path_for() returns the full filesystem path."""
|
|
||||||
backend = LocalStorageBackend(base_dir=str(tmp_path))
|
|
||||||
path = backend.path_for("test.pdf")
|
|
||||||
|
|
||||||
assert path == str(tmp_path / "test.pdf")
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- get_storage_backend() factory ----------
|
|
||||||
|
|
||||||
class TestGetStorageBackend:
|
|
||||||
"""Tests for the storage backend factory function."""
|
|
||||||
|
|
||||||
@patch("SPARC.storage.config")
|
|
||||||
def test_returns_local_backend_by_default(self, mock_config):
|
|
||||||
"""Default config returns LocalStorageBackend."""
|
|
||||||
mock_config.storage_backend = "local"
|
|
||||||
|
|
||||||
backend = get_storage_backend()
|
|
||||||
|
|
||||||
assert isinstance(backend, LocalStorageBackend)
|
|
||||||
|
|
||||||
@patch("SPARC.storage.config")
|
|
||||||
def test_returns_s3_backend_when_configured(self, mock_config):
|
|
||||||
"""Setting storage_backend=s3 returns S3StorageBackend."""
|
|
||||||
mock_config.storage_backend = "s3"
|
|
||||||
mock_config.s3_bucket = "test-bucket"
|
|
||||||
mock_config.s3_endpoint_url = "http://minio:9000"
|
|
||||||
mock_config.s3_access_key = "key"
|
|
||||||
mock_config.s3_secret_key = "secret"
|
|
||||||
|
|
||||||
with patch.dict("sys.modules", {"boto3": MagicMock()}):
|
|
||||||
backend = get_storage_backend()
|
|
||||||
|
|
||||||
assert isinstance(backend, S3StorageBackend)
|
|
||||||
|
|
||||||
@patch("SPARC.storage.config")
|
|
||||||
def test_case_insensitive_backend_selection(self, mock_config):
|
|
||||||
"""Backend selection is case-insensitive."""
|
|
||||||
mock_config.storage_backend = "LOCAL"
|
|
||||||
|
|
||||||
backend = get_storage_backend()
|
|
||||||
|
|
||||||
assert isinstance(backend, LocalStorageBackend)
|
|
||||||
@@ -0,0 +1,388 @@
|
|||||||
|
"""Tests for tracked company admin endpoints and scheduler integration.
|
||||||
|
|
||||||
|
Covers issue #1656:
|
||||||
|
- GET /admin/tracked (list tracked companies)
|
||||||
|
- POST /admin/tracked (add a tracked company)
|
||||||
|
- DELETE /admin/tracked/{company_name} (remove a tracked company)
|
||||||
|
- GET /admin/alerts (list alerts)
|
||||||
|
- scheduler.run_scheduled_analysis() integration
|
||||||
|
|
||||||
|
All tests mock the database layer and use JWT auth fixtures.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from unittest.mock import MagicMock, patch, call
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from SPARC.api import app
|
||||||
|
from SPARC.auth import create_access_token
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client():
|
||||||
|
"""Create test client."""
|
||||||
|
return TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def mock_db():
|
||||||
|
"""Mock the database client used by admin and auth endpoints."""
|
||||||
|
db = MagicMock()
|
||||||
|
|
||||||
|
# Default admin user for auth
|
||||||
|
db.get_user_by_id.return_value = {
|
||||||
|
"id": 1,
|
||||||
|
"email": "admin@test.com",
|
||||||
|
"role": "admin",
|
||||||
|
"created_at": datetime(2025, 1, 1, tzinfo=timezone.utc),
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("SPARC.api.get_db_client", return_value=db), \
|
||||||
|
patch("SPARC.auth.get_db_client", return_value=db):
|
||||||
|
yield db
|
||||||
|
|
||||||
|
|
||||||
|
def _admin_header():
|
||||||
|
"""Create an Authorization header with a valid admin access token."""
|
||||||
|
token = create_access_token(1, "admin@test.com", "admin")
|
||||||
|
return {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
|
||||||
|
def _user_header():
|
||||||
|
"""Create an Authorization header with a regular user access token."""
|
||||||
|
token = create_access_token(2, "user@test.com", "user")
|
||||||
|
return {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- GET /admin/tracked ----------
|
||||||
|
|
||||||
|
class TestListTrackedCompanies:
|
||||||
|
"""GET /admin/tracked"""
|
||||||
|
|
||||||
|
def test_list_tracked_returns_companies(self, client, mock_db):
|
||||||
|
"""Admin can list tracked companies."""
|
||||||
|
mock_db.list_tracked_companies.return_value = [
|
||||||
|
{"company_name": "NVIDIA", "last_patent_count": 120, "last_analyzed": "2025-06-15"},
|
||||||
|
{"company_name": "AMD", "last_patent_count": 80, "last_analyzed": "2025-06-14"},
|
||||||
|
]
|
||||||
|
|
||||||
|
response = client.get("/admin/tracked", headers=_admin_header())
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert len(data) == 2
|
||||||
|
assert data[0]["company_name"] == "NVIDIA"
|
||||||
|
|
||||||
|
def test_list_tracked_empty(self, client, mock_db):
|
||||||
|
"""Returns empty list when no companies are tracked."""
|
||||||
|
mock_db.list_tracked_companies.return_value = []
|
||||||
|
|
||||||
|
response = client.get("/admin/tracked", headers=_admin_header())
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == []
|
||||||
|
|
||||||
|
def test_list_tracked_requires_admin(self, client, mock_db):
|
||||||
|
"""Regular user cannot access tracked companies list."""
|
||||||
|
mock_db.get_user_by_id.return_value = {
|
||||||
|
"id": 2,
|
||||||
|
"email": "user@test.com",
|
||||||
|
"role": "user",
|
||||||
|
"created_at": datetime(2025, 1, 1, tzinfo=timezone.utc),
|
||||||
|
}
|
||||||
|
|
||||||
|
response = client.get("/admin/tracked", headers=_user_header())
|
||||||
|
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
def test_list_tracked_unauthenticated(self, client):
|
||||||
|
"""Unauthenticated request returns 401."""
|
||||||
|
response = client.get("/admin/tracked")
|
||||||
|
assert response.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- POST /admin/tracked ----------
|
||||||
|
|
||||||
|
class TestAddTrackedCompany:
|
||||||
|
"""POST /admin/tracked"""
|
||||||
|
|
||||||
|
def test_add_tracked_company_success(self, client, mock_db):
|
||||||
|
"""Admin can add a company to tracking."""
|
||||||
|
mock_db.add_tracked_company.return_value = {
|
||||||
|
"company_name": "Intel",
|
||||||
|
"last_patent_count": 0,
|
||||||
|
"last_analyzed": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
"/admin/tracked",
|
||||||
|
json={"company_name": "Intel"},
|
||||||
|
headers=_admin_header(),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["company_name"] == "Intel"
|
||||||
|
mock_db.add_tracked_company.assert_called_once_with("Intel")
|
||||||
|
|
||||||
|
def test_add_duplicate_returns_409(self, client, mock_db):
|
||||||
|
"""Adding an already-tracked company returns 409."""
|
||||||
|
mock_db.add_tracked_company.return_value = None
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
"/admin/tracked",
|
||||||
|
json={"company_name": "NVIDIA"},
|
||||||
|
headers=_admin_header(),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 409
|
||||||
|
assert "already tracked" in response.json()["detail"].lower()
|
||||||
|
|
||||||
|
def test_add_tracked_requires_admin(self, client, mock_db):
|
||||||
|
"""Regular user cannot add tracked companies."""
|
||||||
|
mock_db.get_user_by_id.return_value = {
|
||||||
|
"id": 2,
|
||||||
|
"email": "user@test.com",
|
||||||
|
"role": "user",
|
||||||
|
"created_at": datetime(2025, 1, 1, tzinfo=timezone.utc),
|
||||||
|
}
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
"/admin/tracked",
|
||||||
|
json={"company_name": "Intel"},
|
||||||
|
headers=_user_header(),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
def test_add_tracked_empty_name_rejected(self, client):
|
||||||
|
"""Empty company name is rejected by validation."""
|
||||||
|
response = client.post(
|
||||||
|
"/admin/tracked",
|
||||||
|
json={"company_name": ""},
|
||||||
|
headers=_admin_header(),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 422 # Pydantic validation error
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- DELETE /admin/tracked/{company_name} ----------
|
||||||
|
|
||||||
|
class TestRemoveTrackedCompany:
|
||||||
|
"""DELETE /admin/tracked/{company_name}"""
|
||||||
|
|
||||||
|
def test_remove_tracked_company_success(self, client, mock_db):
|
||||||
|
"""Admin can remove a tracked company."""
|
||||||
|
mock_db.remove_tracked_company.return_value = True
|
||||||
|
|
||||||
|
response = client.delete(
|
||||||
|
"/admin/tracked/NVIDIA",
|
||||||
|
headers=_admin_header(),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert "Stopped tracking" in response.json()["message"]
|
||||||
|
mock_db.remove_tracked_company.assert_called_once_with("NVIDIA")
|
||||||
|
|
||||||
|
def test_remove_nonexistent_returns_404(self, client, mock_db):
|
||||||
|
"""Removing a non-tracked company returns 404."""
|
||||||
|
mock_db.remove_tracked_company.return_value = False
|
||||||
|
|
||||||
|
response = client.delete(
|
||||||
|
"/admin/tracked/UnknownCorp",
|
||||||
|
headers=_admin_header(),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert "not found" in response.json()["detail"].lower()
|
||||||
|
|
||||||
|
def test_remove_tracked_requires_admin(self, client, mock_db):
|
||||||
|
"""Regular user cannot remove tracked companies."""
|
||||||
|
mock_db.get_user_by_id.return_value = {
|
||||||
|
"id": 2,
|
||||||
|
"email": "user@test.com",
|
||||||
|
"role": "user",
|
||||||
|
"created_at": datetime(2025, 1, 1, tzinfo=timezone.utc),
|
||||||
|
}
|
||||||
|
|
||||||
|
response = client.delete(
|
||||||
|
"/admin/tracked/NVIDIA",
|
||||||
|
headers=_user_header(),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- GET /admin/alerts ----------
|
||||||
|
|
||||||
|
class TestListAlerts:
|
||||||
|
"""GET /admin/alerts"""
|
||||||
|
|
||||||
|
def test_list_alerts_returns_data(self, client, mock_db):
|
||||||
|
"""Admin can list alerts."""
|
||||||
|
mock_db.list_alerts.return_value = [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"company_name": "NVIDIA",
|
||||||
|
"alert_type": "patent_count_change",
|
||||||
|
"message": "Patent count increased by 25%",
|
||||||
|
"created_at": "2025-06-15T10:00:00Z",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
response = client.get("/admin/alerts", headers=_admin_header())
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert len(data) == 1
|
||||||
|
assert data[0]["alert_type"] == "patent_count_change"
|
||||||
|
|
||||||
|
def test_list_alerts_with_limit(self, client, mock_db):
|
||||||
|
"""Custom limit parameter is passed to the database."""
|
||||||
|
mock_db.list_alerts.return_value = []
|
||||||
|
|
||||||
|
response = client.get("/admin/alerts?limit=10", headers=_admin_header())
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
mock_db.list_alerts.assert_called_once_with(limit=10)
|
||||||
|
|
||||||
|
def test_list_alerts_requires_admin(self, client, mock_db):
|
||||||
|
"""Regular user cannot access alerts."""
|
||||||
|
mock_db.get_user_by_id.return_value = {
|
||||||
|
"id": 2,
|
||||||
|
"email": "user@test.com",
|
||||||
|
"role": "user",
|
||||||
|
"created_at": datetime(2025, 1, 1, tzinfo=timezone.utc),
|
||||||
|
}
|
||||||
|
|
||||||
|
response = client.get("/admin/alerts", headers=_user_header())
|
||||||
|
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Scheduler integration ----------
|
||||||
|
|
||||||
|
class TestSchedulerIntegration:
|
||||||
|
"""Tests for scheduler.run_scheduled_analysis()."""
|
||||||
|
|
||||||
|
def test_no_tracked_companies_skips_analysis(self):
|
||||||
|
"""Scheduler does nothing when no companies are tracked."""
|
||||||
|
mock_db = MagicMock()
|
||||||
|
mock_db.list_tracked_companies.return_value = []
|
||||||
|
|
||||||
|
with patch("SPARC.scheduler.DatabaseClient", return_value=mock_db), \
|
||||||
|
patch("SPARC.scheduler.CompanyAnalyzer") as mock_analyzer_cls:
|
||||||
|
from SPARC.scheduler import run_scheduled_analysis
|
||||||
|
run_scheduled_analysis()
|
||||||
|
|
||||||
|
mock_analyzer_cls.assert_not_called()
|
||||||
|
|
||||||
|
def test_scheduler_analyzes_each_tracked_company(self):
|
||||||
|
"""Scheduler runs analysis for every tracked company."""
|
||||||
|
mock_db = MagicMock()
|
||||||
|
mock_db.list_tracked_companies.return_value = [
|
||||||
|
{"company_name": "NVIDIA", "last_patent_count": 100},
|
||||||
|
{"company_name": "AMD", "last_patent_count": 50},
|
||||||
|
]
|
||||||
|
|
||||||
|
mock_result_nvidia = MagicMock(success=True, patent_count=110)
|
||||||
|
mock_result_amd = MagicMock(success=True, patent_count=55)
|
||||||
|
mock_analyzer = MagicMock()
|
||||||
|
mock_analyzer._analyze_company_safe.side_effect = [mock_result_nvidia, mock_result_amd]
|
||||||
|
|
||||||
|
with patch("SPARC.scheduler.DatabaseClient", return_value=mock_db), \
|
||||||
|
patch("SPARC.scheduler.CompanyAnalyzer", return_value=mock_analyzer):
|
||||||
|
from SPARC.scheduler import run_scheduled_analysis
|
||||||
|
run_scheduled_analysis()
|
||||||
|
|
||||||
|
assert mock_analyzer._analyze_company_safe.call_count == 2
|
||||||
|
mock_db.update_tracked_company.assert_any_call("NVIDIA", 110)
|
||||||
|
mock_db.update_tracked_company.assert_any_call("AMD", 55)
|
||||||
|
|
||||||
|
def test_scheduler_triggers_alert_on_significant_change(self):
|
||||||
|
"""Scheduler stores an alert when patent count changes significantly."""
|
||||||
|
mock_db = MagicMock()
|
||||||
|
mock_db.list_tracked_companies.return_value = [
|
||||||
|
{"company_name": "Tesla", "last_patent_count": 100},
|
||||||
|
]
|
||||||
|
|
||||||
|
mock_result = MagicMock(success=True, patent_count=130) # 30% increase
|
||||||
|
mock_analyzer = MagicMock()
|
||||||
|
mock_analyzer._analyze_company_safe.return_value = mock_result
|
||||||
|
|
||||||
|
with patch("SPARC.scheduler.DatabaseClient", return_value=mock_db), \
|
||||||
|
patch("SPARC.scheduler.CompanyAnalyzer", return_value=mock_analyzer):
|
||||||
|
from SPARC.scheduler import run_scheduled_analysis
|
||||||
|
run_scheduled_analysis()
|
||||||
|
|
||||||
|
mock_db.store_alert.assert_called_once()
|
||||||
|
alert_kwargs = mock_db.store_alert.call_args
|
||||||
|
assert alert_kwargs[1]["company_name"] == "Tesla"
|
||||||
|
assert alert_kwargs[1]["alert_type"] == "patent_count_change"
|
||||||
|
assert alert_kwargs[1]["old_value"] == 100
|
||||||
|
assert alert_kwargs[1]["new_value"] == 130
|
||||||
|
|
||||||
|
def test_scheduler_no_alert_for_small_change(self):
|
||||||
|
"""Scheduler does not alert when change is below threshold."""
|
||||||
|
mock_db = MagicMock()
|
||||||
|
mock_db.list_tracked_companies.return_value = [
|
||||||
|
{"company_name": "Intel", "last_patent_count": 100},
|
||||||
|
]
|
||||||
|
|
||||||
|
mock_result = MagicMock(success=True, patent_count=105) # 5% increase
|
||||||
|
mock_analyzer = MagicMock()
|
||||||
|
mock_analyzer._analyze_company_safe.return_value = mock_result
|
||||||
|
|
||||||
|
with patch("SPARC.scheduler.DatabaseClient", return_value=mock_db), \
|
||||||
|
patch("SPARC.scheduler.CompanyAnalyzer", return_value=mock_analyzer):
|
||||||
|
from SPARC.scheduler import run_scheduled_analysis
|
||||||
|
run_scheduled_analysis()
|
||||||
|
|
||||||
|
mock_db.store_alert.assert_not_called()
|
||||||
|
|
||||||
|
def test_scheduler_handles_analysis_failure(self):
|
||||||
|
"""Scheduler continues when one company fails analysis."""
|
||||||
|
mock_db = MagicMock()
|
||||||
|
mock_db.list_tracked_companies.return_value = [
|
||||||
|
{"company_name": "FailCo", "last_patent_count": 50},
|
||||||
|
{"company_name": "SuccessCo", "last_patent_count": 30},
|
||||||
|
]
|
||||||
|
|
||||||
|
mock_fail_result = MagicMock(success=False, error="API timeout")
|
||||||
|
mock_ok_result = MagicMock(success=True, patent_count=35)
|
||||||
|
mock_analyzer = MagicMock()
|
||||||
|
mock_analyzer._analyze_company_safe.side_effect = [mock_fail_result, mock_ok_result]
|
||||||
|
|
||||||
|
with patch("SPARC.scheduler.DatabaseClient", return_value=mock_db), \
|
||||||
|
patch("SPARC.scheduler.CompanyAnalyzer", return_value=mock_analyzer):
|
||||||
|
from SPARC.scheduler import run_scheduled_analysis
|
||||||
|
run_scheduled_analysis()
|
||||||
|
|
||||||
|
# FailCo should not get updated, SuccessCo should
|
||||||
|
mock_db.update_tracked_company.assert_called_once_with("SuccessCo", 35)
|
||||||
|
|
||||||
|
def test_scheduler_handles_exception_in_analysis(self):
|
||||||
|
"""Scheduler continues even when analysis raises an exception."""
|
||||||
|
mock_db = MagicMock()
|
||||||
|
mock_db.list_tracked_companies.return_value = [
|
||||||
|
{"company_name": "CrashCo", "last_patent_count": 10},
|
||||||
|
{"company_name": "OKCo", "last_patent_count": 20},
|
||||||
|
]
|
||||||
|
|
||||||
|
mock_ok_result = MagicMock(success=True, patent_count=22)
|
||||||
|
mock_analyzer = MagicMock()
|
||||||
|
mock_analyzer._analyze_company_safe.side_effect = [
|
||||||
|
RuntimeError("unexpected error"),
|
||||||
|
mock_ok_result,
|
||||||
|
]
|
||||||
|
|
||||||
|
with patch("SPARC.scheduler.DatabaseClient", return_value=mock_db), \
|
||||||
|
patch("SPARC.scheduler.CompanyAnalyzer", return_value=mock_analyzer):
|
||||||
|
from SPARC.scheduler import run_scheduled_analysis
|
||||||
|
run_scheduled_analysis()
|
||||||
|
|
||||||
|
# OKCo should still be processed
|
||||||
|
mock_db.update_tracked_company.assert_called_once_with("OKCo", 22)
|
||||||
|
mock_db.close.assert_called_once()
|
||||||
Reference in New Issue
Block a user