Skip to content

feat(tests): add integration tests for API endpoints #149#154

Open
Aharshi3614 wants to merge 3 commits into
TENET-DEV-AI:mainfrom
Aharshi3614:feat/integration-tests-149
Open

feat(tests): add integration tests for API endpoints #149#154
Aharshi3614 wants to merge 3 commits into
TENET-DEV-AI:mainfrom
Aharshi3614:feat/integration-tests-149

Conversation

@Aharshi3614

@Aharshi3614 Aharshi3614 commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Description

Implements comprehensive integration tests for all TENET AI API endpoints as specified in issue #149.

Tests cover the full request/response cycle for both the Ingest (port 8000) and Analyzer (port 8100) services across 10 test classes:

  • TestHealthEndpoints - health checks for both services
  • TestAuthFlow - authentication and authorization edge cases
  • TestIngestEndpoint - full ingest happy path
  • TestIngestValidation - input validation and edge cases
  • TestAnalyzerEndpoint - analyzer verdict, schema, error handling
  • TestEventRetrieval - event retrieval by ID, pagination, org isolation
  • TestStatsAndCircuit - stats endpoint and circuit breaker status
  • TestThreatDetection - 12 parametrized accuracy test cases
  • TestPerformance - response time and batch request tests
  • TestErrorHandling - 404, 405, 422 error code verification

Related Issue

Fixes #149

Type of Change

  • New feature (non-breaking change which adds functionality)

How Has This Been Tested?

Ran locally with both services running via uvicorn:

  • Integration tests
  • Manual testing
    pytest tests/integration/test_api_integration.py -v
    Result: 80 passed in 200s

Checklist

  • My code follows the project's code style
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by cubic

Adds end-to-end integration tests for the Ingest and Analyzer services to validate health, auth, core flows, and failure modes across the full request/response cycle. Fulfills issue #149 and reduces false failures by tolerating expected degraded states.

  • New Features

    • Adds tests/integration/test_api_integration.py covering: health (no auth), auth and endpoint access, ingest/analyzer happy paths, detection and validation, event list/get with pagination and org isolation (200/404/503), stats, circuit status, audit export (200/403), performance, and error handling; supports env overrides INGEST_URL, ANALYZER_URL, API_KEY.
  • Bug Fixes

    • Removed hardcoded version checks in health tests and allow 503 in auth-related tests when services are degraded.

Written for commit 3c35bbb. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • Tests
    • Added a comprehensive integration test suite covering API health checks, auth flows, ingest and analyzer endpoint behavior, validation rules, event listing/retrieval and pagination, utility endpoints, threat-detection accuracy, performance benchmarks, and error-handling for unknown routes and invalid input. Tests skip when services are unreachable and include verbose test runner output.

@vercel

vercel Bot commented Jun 10, 2026

Copy link
Copy Markdown

@Aharshi3614 is attempting to deploy a commit to the s3dfx-cyber's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 54082e32-a8fe-49d0-8852-6c0b845452bd

📥 Commits

Reviewing files that changed from the base of the PR and between 9d33a05 and 3c35bbb.

📒 Files selected for processing (1)
  • tests/integration/test_api_integration.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/integration/test_api_integration.py

📝 Walkthrough

Walkthrough

This PR adds a comprehensive Python integration test suite for TENET AI API endpoints, including environment-driven configuration, a health-check fixture, payload helper, and tests covering health, auth, ingest/analyzer validation, event retrieval, utility endpoints, threat detection, performance, and error handling.

Changes

Integration Test Suite for TENET AI API Endpoints

Layer / File(s) Summary
Test Infrastructure Setup
tests/integration/test_api_integration.py (lines 1–75)
Module documentation, environment configuration for URLs and API keys, shared llm_payload() helper, _service_up() health probe, and require_services() autouse fixture that skips all tests if either service is unreachable.
Health and Authentication Tests
tests/integration/test_api_integration.py (lines 81–192)
TestHealthEndpoints validates status codes and response schema for both services' /health endpoints without authentication; TestAuthFlow verifies HTTP 401/403 behavior for missing, invalid, and valid API keys across protected ingest and analyzer routes and utility endpoints.
Ingest Endpoint Tests
tests/integration/test_api_integration.py (lines 197–401)
TestIngestEndpoint tests /v1/events/llm happy path with classification outcomes (benign/blocked/malicious/suspicious), required fields, UUID validity, optional system_prompt/metadata, and message content checks. TestIngestValidation covers empty/whitespace prompts, missing fields, prompt max-length boundary acceptance/rejection, non-JSON content handling, and case-insensitive injection pattern detection.
Analyzer Endpoint Tests
tests/integration/test_api_integration.py (lines 406–522)
TestAnalyzerEndpoint tests /v1/analyze verdict/threat type/risk/confidence fields across multiple threat categories, validates numeric range constraints, verifies detection expectations for injection/jailbreak/data extraction, and handles empty/missing prompts and optional context.
Event Retrieval and Data Access
tests/integration/test_api_integration.py (lines 527–609)
TestEventRetrieval tests list endpoint pagination/schema, retrieves created events by ID with graceful degraded-state handling, validates 404 for nonexistent IDs, and verifies org isolation—events are not visible with different API keys.
Utility Endpoints and Threat Detection
tests/integration/test_api_integration.py (lines 614–703)
TestStatsAndCircuit validates /v1/stats, /v1/circuit-status, and /v1/audit/export field presence and status codes for degraded environments. TestThreatDetection uses parametrized known-prompt assertions to verify expected blocked/verdict behavior.
Performance and Error Handling
tests/integration/test_api_integration.py (lines 709–829)
TestPerformance measures elapsed time for ingest/analyzer/health with thresholds and sequential batch ingest with failure tracking. TestErrorHandling verifies HTTP status codes for unknown routes, wrong methods, invalid query parameters, and JSON-parseability of auth-error responses. A __main__ runner executes pytest verbosely.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • #149: This PR implements the integration test suite objectives including fixtures, endpoint coverage, authentication/authorization validation, threat detection tests, and error-case coverage described in the issue.

Poem

🐰 A rabbit hopped through endpoints bright,
Testing health and auth's might,
Ingest and analyze with care,
Errors parsed and metrics fair,
Integration checks, the suite's delight! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.39% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'feat(tests): add integration tests for API endpoints #149' clearly and concisely summarizes the main change—adding integration tests for API endpoints.
Description check ✅ Passed The PR description is comprehensive and follows the template structure with summary, related issue reference, type of change, testing details, and completed checklist items.
Linked Issues check ✅ Passed The PR fulfills all primary coding requirements from issue #149: comprehensive integration tests covering endpoints, auth flows, detection with payloads, error handling, and full request/response cycles across 10 test classes.
Out of Scope Changes check ✅ Passed All changes are in-scope integration tests for API endpoints. The PR adds only test code in tests/integration/test_api_integration.py with no modifications to production code or unrelated functionality.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 1 file

Re-trigger cubic

@S3DFX-CYBER S3DFX-CYBER requested a review from Preetham404 June 10, 2026 12:08

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/integration/test_api_integration.py`:
- Around line 88-92: The test test_ingest_health_response_schema currently
asserts an exact version string ("0.1.0") which will break on normal version
bumps; change the assertion in test_ingest_health_response_schema (and the
similar assertions around lines 101-105) to validate the version more
flexibly—e.g., assert that data["version"] is a non-empty string or matches a
semantic version pattern, or compare it against the package/app runtime version
constant if available—so the test verifies format/presence rather than a
hard-coded value.
- Around line 150-167: The tests test_valid_key_accepted_on_ingest and
test_valid_key_accepted_on_analyzer currently assert a strict 200 response,
coupling auth checks to downstream availability; update both assertions to
accept successful auth responses even if downstream is degraded by asserting
r.status_code is in an allowed set (e.g., {200, 503}) or by asserting the
response is not an authentication failure (e.g., not 401/403), so the tests only
validate that VALID_HEADERS are accepted rather than the full service health.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: eae01221-6742-43f1-86e5-c725a7210263

📥 Commits

Reviewing files that changed from the base of the PR and between 721686f and 9d33a05.

📒 Files selected for processing (1)
  • tests/integration/test_api_integration.py

Comment on lines +88 to +92
def test_ingest_health_response_schema(self):
data = requests.get(f"{INGEST_URL}/health", timeout=5).json()
assert data["service"] == "ingest"
assert data["version"] == "0.1.0"
assert data["status"] in ("healthy", "degraded")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid hard-coding exact service version in health schema assertions.

Pinning "0.1.0" makes these tests fail on normal version bumps even when the endpoint contract is still valid.

Proposed fix
-        assert data["version"] == "0.1.0"
+        assert isinstance(data.get("version"), str) and data["version"]
...
-        assert data["version"] == "0.1.0"
+        assert isinstance(data.get("version"), str) and data["version"]

Also applies to: 101-105

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/integration/test_api_integration.py` around lines 88 - 92, The test
test_ingest_health_response_schema currently asserts an exact version string
("0.1.0") which will break on normal version bumps; change the assertion in
test_ingest_health_response_schema (and the similar assertions around lines
101-105) to validate the version more flexibly—e.g., assert that data["version"]
is a non-empty string or matches a semantic version pattern, or compare it
against the package/app runtime version constant if available—so the test
verifies format/presence rather than a hard-coded value.

Comment on lines +150 to +167
def test_valid_key_accepted_on_ingest(self):
r = requests.post(
f"{INGEST_URL}/v1/events/llm",
headers=VALID_HEADERS,
json=llm_payload("Hello world"),
timeout=5,
)
assert r.status_code == 200

def test_valid_key_accepted_on_analyzer(self):
r = requests.post(
f"{ANALYZER_URL}/v1/analyze",
headers=VALID_HEADERS,
json={"prompt": "Hello world"},
timeout=5,
)
assert r.status_code == 200

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Decouple valid-key auth checks from downstream service availability.

These tests currently require 200 only; they can fail when auth passes but dependencies are degraded (e.g., transient 503), which turns auth checks into infrastructure-flakiness checks.

Proposed fix
-        assert r.status_code == 200
+        assert r.status_code in (200, 503)

...
-        assert r.status_code == 200
+        assert r.status_code in (200, 503)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/integration/test_api_integration.py` around lines 150 - 167, The tests
test_valid_key_accepted_on_ingest and test_valid_key_accepted_on_analyzer
currently assert a strict 200 response, coupling auth checks to downstream
availability; update both assertions to accept successful auth responses even if
downstream is degraded by asserting r.status_code is in an allowed set (e.g.,
{200, 503}) or by asserting the response is not an authentication failure (e.g.,
not 401/403), so the tests only validate that VALID_HEADERS are accepted rather
than the full service health.

@S3DFX-CYBER

Copy link
Copy Markdown
Collaborator

@Aharshi3614 needs fixes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement Integration Tests for TENET AI API Endpoints

2 participants