Skip to content

Repository files navigation

Java to Python Test Suite

Verification-first test infrastructure for secure, dependency-aware Java to Python translation services.

LicenseLast CommitIssuesPythonPytestSecurity Tests

Executive Summary

This project uses a Python + pytest stack because it maximizes test expressiveness, async API coverage, and security-focused validation in one cohesive framework. The suite is intentionally built around comparison and traceability: each major requirement is represented in marker groups, assertion patterns, dependency ordering tests, and visual models.

Why This Stack, How It Is Used, and Benefits

TechnologyWhy UsedHow Used in This SuiteBenefit Over Alternatives
Python 3.11+Fast iteration and excellent testing ecosystemExecutes all test layers and fixture logicLower friction than Java/JUnit for mixed async + security test authoring
pytestMarker-based structure and fixture systemSeparates unit/integration/correctness/negative/adversarial pipelinesBetter parametrization and fixture ergonomics than unittest
pytest-asyncioNative async compatibilityRuns async endpoint tests without custom event-loop wrappersCleaner than ad-hoc loop management
httpx + ASGITransportIn-process API contract testingCalls API endpoints with dependency overrides and mock backendsFaster and more deterministic than external server + requests
cryptography + PyJWTRealistic auth-path verificationGenerates RSA keys and signs test JWTs at runtimeStronger coverage than static token-only tests
javalangJava structure awareness in validation workflowsSupports parser-oriented assertions in unit testsMore reliable than regex-only Java parsing checks

Important

The suite verifies not only correctness, but also translation safety and dependency order requirements, including base-class-before-subclass guarantees through topological sorting tests.

Table of Contents

Overview

This repository is a dedicated test harness for a Java-to-Python translation service. It validates parser behavior, method/type fidelity, API contract integrity, authorization controls, guardrail enforcement, and adversarial resilience. It is designed for teams that need reproducible quality and security checks before releasing translation features.

Important

The suite assumes an external orchestrator source path and environment variables are available as configured in conftest.py.

Core value for this project:

  • Confirms required behavior with explicit assertions (not heuristic checks only).
  • Compares expected ordering and output properties against actual responses.
  • Detects failures in dependency ordering and cycle handling early.
  • Verifies that translation order favors reusable base components before dependents.

(back to top)

Requirements to Validation Mapping

RequirementImplementation FocusEvidence in Test SuiteOutcome Verified
Parse Java artifacts safelyParser and class-info extraction pathstests/unit/test_java_parsing.pyAST/data extraction is stable for normal and malformed inputs
Build dependency graph correctlyIntra-project edge constructiontests/unit/test_dependency_graph.pyNo self-loops, no JDK noise, valid class map
Sort translation order by dependencyTopological ordering logictests/unit/test_topological_sort.pyDependencies appear before dependent classes
Translate base classes before subclassesOrdering invariant in project translation plantests/unit/test_topological_sort.py and tests/integration/test_project_translate_api.pyBase abstractions precede concrete subclasses/services
Detect cycles without dropping filesCycle fallback behaviortests/adversarial/test_circular_dependencies.py and unit cycle testshad_cycle is true and all files remain represented
Block unsafe or manipulative inputInput guardrailstests/adversarial/test_prompt_injection.py and tests/unit/test_guardrails.pyInjection/secret patterns rejected before model path
Enforce RBAC and policy boundariesJWT + permission checkstests/negative/test_rbac_enforcement.pyUnauthorized roles/actions are denied

(back to top)

Requirements Verification and Validation

This suite applies both verification and validation:

  • Verification asks: are we building the system right against explicit requirements?
  • Validation asks: are we building the right behavior for secure translation operations?

V&V Strategy Matrix

Requirement AreaVerification MethodValidation MethodPass CriteriaPrimary Evidence
Dependency graph correctnessUnit assertions on graph edges and node invariantsIntegration checks of API dependency outputNo self-loops, no missing files, dependency-first ordertests/unit/test_dependency_graph.py, tests/integration/test_project_translate_api.py
Topological ordering (base before subclass)Unit invariant checks for order index relationshipsProject-level translate API response order checksFor every edge A depends on B, index(B) < index(A)tests/unit/test_topological_sort.py, tests/integration/test_project_translate_api.py
Cycle detection robustnessUnit and adversarial cycle test scenariosEnd-to-end circular project request handlinghad_cycle true on cyclic input, all files retained in outputtests/adversarial/test_circular_dependencies.py, tests/unit/test_topological_sort.py
Security guardrailsUnit and adversarial pattern blocking testsAPI-level blocked request behavior checksInjection and credential patterns rejected before unsafe processingtests/unit/test_guardrails.py, tests/adversarial/test_prompt_injection.py
RBAC and auth correctnessNegative role/permission testsUnauthorized API paths return denied responsesRole permissions enforced with no privilege escalationtests/negative/test_rbac_enforcement.py, integration auth tests
Output structure fidelityCorrectness tests over syntax/import/signaturesWorkflow-level usage consistency checksOutputs remain parseable and structurally aligned to expectationstests/correctness/*.py

Verification Pipeline

flowchart TD
A[Requirements] --> B[Unit Verification]
B --> C[Integration Verification]
C --> D[Negative and Adversarial Verification]
D --> E[Validation Against Runtime Behaviors]
E --> F[Release Confidence Decision]
Loading

Validation Acceptance Gates

GateScopeCommand PatternMinimum Acceptance
Gate 1Core logic verificationpytest -m unit -qAll dependency/order/parser tests pass
Gate 2API contract verificationpytest -m integration -qEndpoint contract fields and ordering checks pass
Gate 3Security validationpytest -m negative -q && pytest -m adversarial -qRBAC, injection, and egress/model policy checks pass
Gate 4Output quality validationpytest -m correctness -qOutput syntax/structure/import quality checks pass
Gate 5Full-system confidencepytest -qNo regressions across all marker groups

Traceability Notes

  • Requirement-to-test traceability is explicit through marker groups and targeted modules.
  • Visualization-to-requirement traceability is captured by architecture, object model, and dependency diagrams.
  • Algorithm-to-requirement traceability is captured by Kahn ordering assertions that enforce base-before-subclass translation.

Note

V&V is strongest when failures are triaged by marker group first, then by requirement area, so remediation stays requirement-focused rather than only test-focused.

(back to top)

Architecture

flowchart LR
A[Fixture Corpus: Java Inputs] --> B[Pytest Marker Groups]
B --> C[Unit Validations]
B --> D[Integration Endpoint Contracts]
B --> E[Negative Security and RBAC]
B --> F[Adversarial Guardrail Tests]
C --> G[Dependency Graph + Topological Sort Validation]
D --> H[Translate and Translate-Project API Behavior]
E --> H
F --> H
G --> I[Confidence in Ordering and Requirements]
H --> I
Loading

Architecture intent:

  • Marker groups isolate concerns so each risk area is testable independently.
  • Unit tests validate deterministic algorithmic behavior (graph and order).
  • Integration tests confirm API contract fields like dependency_order and had_cycle.
  • Security suites ensure unsafe requests fail fast and auditable paths stay intact.

(back to top)

Object Model

classDiagram
class FileEntry {
+string filename
+string source
+class_info
+set dependencies
+int order
}
class ProjectTranslationPlan {
+list ordered_files
+map class_map
+bool had_cycle
}
class JavaClassInfo {
+string name
+bool is_interface
+bool is_abstract
+set imports
+set methods
}
ProjectTranslationPlan "1" --> "many" FileEntry : contains
FileEntry --> JavaClassInfo : parsed_from
Loading

How this model helps:

  • Makes ordering state explicit (order, dependencies, had_cycle).
  • Supports comparison between parsed structure and output expectations.
  • Enables requirement-level assertions that are easy to reason about in tests.

(back to top)

Dependency Graph and Topological Sort

The translation planner builds a directed dependency graph where each node is a class/file and edges represent prerequisite relationships (for example, subclass depends on base class).

flowchart TD
A[AbstractProcessor] --> B[PaymentProcessor]
C[Order] --> D[OrderService]
E[IRepository] --> F[OrderRepository]
C --> F
Loading

The expected translation order is dependency-first:

  1. Base abstractions and interfaces.
  2. Core domain models.
  3. Concrete implementations and services.

This is why tests verify examples such as Order before OrderService and AbstractProcessor before PaymentProcessor.

Dependency ordering checkpoints used by the suite
Ordering CheckWhy It MattersTest Evidence
Order before OrderServiceService methods require model definitions firstUnit and integration ordering assertions
AbstractProcessor before PaymentProcessorSubclass translation needs base contract contextUnit topological ordering assertions
IRepository before OrderRepositoryInterface constraints should be available before implementationUnit topological ordering assertions
Cycle path still returns all filesProduction robustness under imperfect source graphsCircular dependency adversarial/unit tests

(back to top)

Why Kahn's Algorithm Matters Here

What is Kahn's Algorithm? (Layman's Explanation)

Imagine you have a to-do list with dependencies:

  • Task A: "Learn Python" (must do first)
  • Task B: "Build a web app" (depends on Task A - you need Python knowledge)
  • Task C: "Deploy the app" (depends on Task B - you need a working app to deploy)

You can't do Task B until Task A is done. You can't do Task C until Task B is done. Kahn's algorithm automatically figures out the correct order to do tasks when there are many interdependencies.

In our case, we have Java classes instead of tasks:

  • Order.java (no dependencies - do first)
  • OrderService.java (depends on Order)
  • OrderRepository.java (depends on both Order and OrderService)

Kahn's algorithm ensures Order.java is translated to Python before OrderService.java, which is translated before OrderRepository.java.

How Kahn's Algorithm Works (Step by Step)

Step 1: Count Prerequisites (In-Degree) For each class, count how many other classes it needs:

Order: 0 dependencies (no prerequisites)
OrderService: 1 dependency (depends on Order)
OrderRepository: 2 dependencies (depends on Order and OrderService)

Step 2: Find Classes with Zero Prerequisites Start with classes that don't depend on anything:

Queue = [Order] (has 0 dependencies)

Step 3: Process One Class at a Time

  • Take Order from the queue
  • Tell all classes that depend on Order: "Order is done!"
  • OrderService loses one dependency (Order is now satisfied)
  • OrderRepository loses one dependency (Order is now satisfied)
  • Check if any class now has zero dependencies:
    • OrderService: 1 - 1 = 0 dependencies left → Add to queue!
Processed = [Order]
Queue = [OrderService]

Step 4: Repeat

  • Take OrderService from the queue
  • Tell OrderRepository: "OrderService is done!"
  • OrderRepository: 2 - 1 = 1 dependency left (still needs Order, but it's already done)
    • Actually, Order was already processed, so OrderRepository should have 1 left
    • But both its dependencies (Order, OrderService) are done → Add to queue!
Processed = [Order, OrderService]
Queue = [OrderRepository]
  • Take OrderRepository from the queue
  • No classes depend on it
Processed = [Order, OrderService, OrderRepository]
Queue = [] (empty - we're done!)

Step 5: Detect Cycles If some classes remain with unmet dependencies after processing everything, there's a circular dependency (cycle):

  • A depends on B
  • B depends on C
  • C depends on A (creates a circle!)

These classes can't be properly ordered, but the algorithm includes them anyway so you're aware of the problem.

Algorithm Pseudo-Code

function KahnSort(graph):
// Count how many dependencies each node has
for each node in graph:
in_degree[node] = count of nodes it depends on
// Find who depends on whom (reverse lookup)
for each edge (A depends on B):
dependents[B].add(A)
// Start with nodes that have no dependencies
queue = [all nodes where in_degree = 0]
result = []
// Process nodes in order
while queue is not empty:
current = queue.pop()
result.add(current)
// For each node that depends on current:
for each dependent in dependents[current]:
dependent.in_degree -= 1
if dependent.in_degree = 0:
queue.add(dependent)
// Check for cycles
if result.size < graph.size:
had_cycle = TRUE
// Add remaining nodes (they're in a cycle)
result.add(remaining nodes)
return (result, had_cycle)

Real-World Code Example from This Project

When we have Java files:

// Order.javapublicclassOrder { ... }
// OrderService.javapublicclassOrderService {
privateOrderorder; // depends on Order!
...
}
// OrderRepository.javapublicinterfaceOrderRepository {
OrderfindById(Stringid); // depends on Order!
}

Kahn's algorithm outputs: [Order, OrderService, OrderRepository]

This guarantees:

  • Order is translated first
  • OrderService can reference Order class (exists in Python)
  • OrderRepository can reference Order class (exists in Python)

Why Not Just Random Order?

If we translated OrderService before Order:

classOrderService:
def__init__(self):
self.order: Order# ERROR! Order not defined yet!

This fails because Order doesn't exist yet. Kahn's algorithm prevents this.

High-level behavior (The original formulation):

  1. Compute in-degree for each node.
  2. Start with nodes that have in-degree 0 (no unmet dependencies).
  3. Remove processed nodes and decrement neighbors' in-degree.
  4. Continue until all nodes are processed.
  5. If nodes remain with non-zero in-degree, a cycle exists.

In this test suite, that behavior directly supports translation correctness:

  • Guarantees dependency-first ordering for base classes and shared contracts.
  • Prevents subclass-first generation that can create invalid imports/signatures.
  • Detects cycles early while still preserving a complete output list for diagnostics.
sequenceDiagram
participant Graph as Dependency Graph
participant Kahn as Kahn Sort (In-Degree)
participant Planner as Translation Planner
Graph->>Kahn: Nodes + dependency edges
Kahn->>Kahn: 1. Compute in-degree (# dependencies per node)
Kahn->>Kahn: 2. Find nodes with in-degree = 0
Kahn->>Kahn: 3. Process each in order, decrement neighbors
Kahn->>Kahn: 4. Continue until queue empty
Kahn->>Kahn: 5. Check if nodes remain (cycle detection)
Kahn-->>Planner: dependency_order list
Kahn-->>Planner: had_cycle flag
Planner-->>Planner: translate base classes before subclasses
Loading

Tip

Kahn's approach is deterministic and testable: each assertion can verify that every dependency index is lower than its dependent index. The algorithm guarantees: if class B must be translated before class A (A depends on B), then index(B) < index(A) in the output list.

(back to top)

Visualization as a Verification Tool

Visualizations in this README are not decorative. They reduce ambiguity when comparing implemented function behavior against requirements.

VisualizationConfirmsComparison Benefit
Architecture flowchartEnd-to-end validation pipelineQuickly spots missing validation layers
Object model diagramData structures and relationshipsConfirms required fields exist for assertions
Dependency graph diagramExpected dependency directionMakes ordering mistakes obvious during review
Kahn sequence diagramAlgorithm steps and outputsAligns function behavior with requirement statements

How this helps requirement comparison:

  • Requirement text says dependency-first translation.
  • Graph + sequence diagrams show exactly how dependency-first behavior is enforced.
  • Unit tests then compare actual order indices to required invariants.
  • Integration tests compare API dependency_order to expected file precedence.

(back to top)

Technology Stack Decision Matrix

Stack PartChosen OptionAlternativeWhy Chosen for This ProjectPractical Benefit
Test frameworkpytestunittestMarker groups and fixture composition scale better for layered suitesFaster targeted runs and cleaner test organization
Async testingpytest-asynciocustom loop managementNative async test support without boilerplateLower maintenance and fewer flaky async tests
API clienthttpx + ASGITransportrequests + live serverIn-process execution keeps integration tests deterministicBetter speed and less CI networking variability
Auth validationcryptography + PyJWTstatic token stringsRuntime key/signature generation tests real verification pathsHigher confidence in RBAC behavior
Java structure parsingjavalangregex parsingStructural parsing avoids brittle text matchingMore robust dependency and class extraction checks
Technology usage map by test concern
Test ConcernMain TechnologyRole
Parser and graph correctnesspytest + javalangValidates class extraction and dependency edges
Endpoint behaviorpytest-asyncio + httpxExercises translate endpoints and payload contracts
RBAC and token handlingcryptography + PyJWTGenerates realistic signed JWTs for role checks
Guardrails and adversarial handlingpytest markers + fixturesEnforces injection/secret blocking expectations

(back to top)

Testing & Quality Assurance Tool Integration Matrix

This test suite can be enhanced through integration with specialized testing, analysis, and verification tools. Below are recommended integrations organized by capability:

Static Code Analysis Tools (Top-to-Bottom Requirements Verification)

ToolPurposeIntegration PointValidatesPython SupportCost Model
Klocwork (Perforce)SAST - Security, quality, reliabilityPre-commit hooks, CI/CD pipelineSecurity vulnerabilities, code defects, reliability issues✅ YesEnterprise/Commercial
SonarQubeCode quality & maintainabilityPost-test analysis, quality gatesCode quality, technical debt, duplication, test coverage✅ YesOpen-source/Commercial
Checkmarx (SAST)Enterprise security scanningPipeline integration, complianceDeep vulnerability analysis, compliance standards, OWASP✅ YesEnterprise/Commercial
Coverity (Synopsys)Deep static analysisBuild integration, incremental analysisMemory/security issues, race conditions✅ YesEnterprise/Commercial
BanditPython security scanningPre-commit, CI integrationPython security issues, hardcoding secrets✅ Yes (Python-specific)Open-source
ESLint/PylintLinting & styleGit hooks, pre-flight checksCode style, suspicious patterns, imports✅ Yes (Pylint)Open-source

Why multiple tools? Each excels in different domains:

  • Klocwork for security-first orgs needing compliance-grade SAST
  • SonarQube for quality gates and technical debt tracking
  • Checkmarx when regulatory/enterprise security is primary
  • Bandit/Pylint for lightweight pre-commit gating

Test Execution & Measurement Tools

ToolPurposeIntegration PointMetrics CollectedUse CaseCost
pytest (current)Unit/integration test frameworkDirect test runnerPass/fail, execution timeCore test executionOpen-source
pytest-covCode coverage measurementCoverage plugin, post-testLine/branch coverage %Verify guardrails touch all code pathsOpen-source
CodecovCoverage tracking & trendingCI upload, GitHub integrationCoverage trends, PR diffsLong-term quality visibilityFree/Pro
DatadogContinuous testing & monitoringAPI instrumentationTest performance, flakinessDetect regression patternsCommercial
LoadRunnerPerformance and load testingScheduled pipeline stage, release gateResponse times, throughput, error rate, SLA complianceValidate API under expected translation volumeCommercial

Recommended first addition:pytest-cov to verify that guardrail code paths (input_guard, output_guard, provider_lock) are fully exercised.

Mutation Testing (Test Quality Verification)

ToolPurposeHow It WorksValue for This SuitePython Support
StrykerMutation testing frameworkModifies code, reruns testsVerifies tests catch real bugs✅ Yes
PITBytecode mutation (Java/JVM)Mutates compiled bytecodeValidates our test harness quality✅ (via JVM)

Application to this suite: Run mutation tests on guardrails code (input_guard, output_guard, provider_lock) to ensure rejection logic is properly tested.

Dependency & Supply Chain Security

ToolPurposeScansIntegrationPython Support
SnykDependency vulnerability scanningrequirements.txt, package manifestsPre-commit, PR checks, CI✅ Yes
OWASP Dependency-CheckKnown vulnerability databaseDependencies, transitiveCLI, Maven/Gradle, CI✅ Yes
Black Duck (Synopsys)License/composition analysisCodebases, dependenciesCI pipeline, compliance✅ Yes
pip-auditPython package auditingpip requirementsGitHub Actions, pre-commit✅ Yes (Python-specific)

Why this matters: fastapi, pytest, javalang, and cryptography dependencies must remain secure. Snyk + pip-audit provide light/fast scanning; Black Duck for enterprise compliance.

Requirements Verification & Traceability Tools

ToolFunctionIntegrationTraceabilityCompliance
Azure DevOps Test PlansRequirements↔Tests mappingWork items, test suitesBi-directional linksCMMI/ISO ready
Jira XrayTest management within JiraIssues, test runs, coverageRequirement→Test→ResultRegulatory (FDA, etc.)
TestRailStandalone test managementAPI, CI integrationTest case traceabilitySOC 2, HIPAA compatible
ReqIF EditorRequirements interchange formatFile-based traceabilitySpec→Design→TestAutomotive (ASIL) standard

Current project: README.md serves as living requirements. For regulated environments, migrate to one of above tools to create formal traceability matrix.

DevOps & CI/CD Integration Points

Pipeline StageTool CategoryRecommended ToolWhat It Checks
Pre-commitLinting + SecurityBandit, Pylint, Pre-commit hooksFast rejection of obvious issues
BuildStatic AnalysisKlocwork, SonarQube scannerDeep security & quality analysis
TestExecution + Coveragepytest + pytest-covFunctional correctness, coverage %
MutationTest QualityStryker or PITAre tests strong enough?
Dependency ScanSupply ChainSnyk + pip-auditKnown vulnerabilities in deps
ComplianceReportingSonarQube/Checkmarx dashboardsMeet quality gates, audit trail

Top-to-Bottom Requirements Verification Example Flow

graph TD
A[Requirements<br/>README.md] -->|Defined as test markers| B[Test Suite<br/>387 tests]
B -->|Run on every commit| C[pytest<br/>Unit/Int/Correctness]
C -->|Coverage tracked| D[pytest-cov<br/>Code coverage %]
D -->|Trending| E[Codecov<br/>Historical view]
C -->|Mutation test| F[Stryker<br/>Test quality]
F -->|Validates| G{Tests strong<br/>enough?}
G -->|Yes| H[SonarQube<br/>Quality gates]
C -->|Security scan| I[Klocwork/Checkmarx<br/>Vulnerability detection]
I -->|Verify| J[Zero high-risk<br/>findings]
K[requirements.txt] -->|Supply chain scan| L[Snyk/pip-audit<br/>Dependency check]
H -->|Release gate| M[Deploy<br/>with confidence]
J -->|Security approval| M
L -->|No vulns found| M
style A fill:#e1f5ff
style M fill:#c8e6c9
Loading

This flow ensures:

  1. Requirements are explicit (README)
  2. Tests verify requirements (pytest suite)
  3. Tests are strong (mutation testing)
  4. Code is secure (static analysis + SAST)
  5. Dependencies are safe (supply chain scanning)
  6. Quality gates passed (SonarQube)

(back to top)

Integration Implementation Patterns

1. Code Coverage with pytest-cov

Add coverage measurement to verify all guardrail code is exercised:

# Run tests with coverage
pytest --cov=guardrails --cov=core --cov-report=html --cov-report=term
# Verify minimum coverage threshold
pytest --cov=guardrails --cov-fail-under=90

In CI/CD (GitHub Actions example):

- name: Run tests with coveragerun: pytest --cov=guardrails --cov=core --cov-report=xml
- name: Upload coverage to Codecovuses: codecov/codecov-action@v3with:
files: ./coverage.xml

Why this matters: Guardrails (input_guard.py, output_guard.py) must have zero uncovered branches to ensure all security checks are tested.

2. Security Scanning with Bandit (Lightweight Pre-commit)

Add Python security scanning before commit:

# Install Bandit
pip install bandit
# Scan project
bandit -r guardrails/ core/ api/ tools/ -f json -o bandit-report.json
# Fail on medium+ severity
bandit -r . -ll # -ll = medium level and above

Pre-commit hook (.pre-commit-config.yaml):

- repo: https://github.com/PyCQA/banditrev: 1.7.5hooks:
- id: banditargs: ['-ll'] # Medium severity minimumexclude: tests/

Focus areas: Detect hardcoded secrets, SQL injection patterns, insecure random usage in guardrails and auth modules.

3. Dependency Vulnerability Scanning

Quick setup with pip-audit (Python-specific):

# Install pip-audit
pip install pip-audit
# Check dependencies
pip-audit --desc # Show vulnerability descriptions# In CI, fail on high-severity
pip-audit --fail-on high

GitHub Actions integration:

- name: Check dependencies for vulnerabilitiesrun: pip-audit --fail-on high

Critical dependencies to monitor:

  • fastapi (API framework)
  • cryptography (JWT/RBAC)
  • javalang (Java parsing)
  • pydantic (data validation)

4. Static Code Quality with SonarQube (Optional, Enterprise)

For organizations with SonarQube instance:

# Install SonarScanner
pip install sonarscan
# Run analysis (requires sonar.projectKey, sonar.host.url, sonar.login)
sonar-scanner \
-Dsonar.projectKey=java-to-python \
-Dsonar.host.url=https://sonarqube.company.com \
-Dsonar.login=$SONAR_TOKEN

Quality gate conditions:

  • Coverage > 80%
  • Duplicated lines < 5%
  • Code smells < 10
  • No critical issues

5. Mutation Testing with Stryker (Test Validation)

Verify that tests catch real bugs by mutating code:

# Install Stryker for Python
pip install mutmut
# Run mutation tests on guardrails
mutmut run --paths-to-mutate=guardrails
# Generate HTML report
mutmut html

Example: Test that input_guard.py rejection logic is properly tested:

mutmut run --paths-to-mutate=guardrails/input_guard.py \
--tests-dir=tests/adversarial

Success criteria: > 80% mutation score (tests kill > 80% of mutants)

6. Compliance Reporting & Traceability (Regulated Environments)

For organizations requiring formal verification:

Current state (README-based):

README.md
├── Requirements section
├── Test suite breakdown
├── Unit/Integration/Correctness/Negative/Adversarial breakdown
└── Maps to test files

Migrate to (TestRail example):

  1. Create test plan in TestRail
  2. Link each test case to requirement ID
  3. Run tests via API
  4. Auto-generate compliance report
# Example: Link test to requirement# TestRail API: Create test case run with requirement traceabilityPOST/api/v2/add_result_for_case/1/123
{
"status_id": 1, # passed"comment": "Verifies Req-002: Dependency ordering",
"custom_requirement_id": "REQ-002"
}

7. LoadRunner Performance Integration

LoadRunner fits this project as the dedicated non-functional gate for the FastAPI endpoints:

EndpointSuggested LoadRunner TransactionDefault SLAPrimary AssertionCurrent Project Hook
/api/v1/translatetranslate250 msMedian and p95 stay within SLAAudit log writes loadrunner transaction summary
/api/v1/translate-projecttranslate_project500 msMulti-file requests stay below release thresholdAudit log writes per-request performance budget status
/api/v1/translate-requirementstranslate_requirements250 msRequirements scaffolding stays responsiveAudit log writes Six Sigma-style CTQ metrics

This repository now exposes LoadRunner-friendly transaction metadata in audit records:

{
"action": "translate",
"latency_ms": 83.2,
"performance_budget_ms": 250,
"performance_status": "within_control",
"loadrunner": {
"transaction": "translate",
"response_time_ms": 83.2,
"sla_ms": 250,
"passed": true
}
}

That makes it straightforward to compare internal audit data with external LoadRunner runs and to use the same transaction names in performance dashboards.

7.1 Release Dashboard Endpoint

The service now includes a small read-only release dashboard endpoint at /api/v1/audit-report.

It aggregates the JSONL audit log into a single release-oriented summary:

Dashboard SectionAggregatesWhy It Matters For Release Decisions
summaryTotal requests, ok requests, blocked requests, unique actionsQuick go/no-go snapshot
actionsPer-endpoint request count, average latency, p95 latency, LoadRunner pass rateShows which endpoint is drifting
performanceGlobal average latency, p95 latency, performance status countsHighlights SLA breaches and warning trends
qualityCTQ pass rates, average DPMO, sigma-band counts, control-state countsConverts raw audit events into process-quality signals

Example usage:

curl -H "Authorization: Bearer <token>" http://localhost:8000/api/v1/audit-report

Example response shape:

{
"summary": {
"total_requests": 24,
"ok_requests": 21,
"blocked_requests": 3,
"unique_actions": 3
},
"actions": {
"translate": {
"requests": 12,
"avg_latency_ms": 85.4,
"p95_latency_ms": 140.2,
"loadrunner_pass_rate": 1.0
}
},
"performance": {
"avg_latency_ms": 91.7,
"p95_latency_ms": 151.6,
"performance_status_counts": {
"within_control": 22,
"warning": 1,
"breach": 1
},
"loadrunner_pass_rate": 0.958
},
"quality": {
"ctq_metrics": {
"reliability": {
"pass_count": 23,
"total": 24,
"pass_rate": 0.958
}
},
"avg_dpmo": 13888.889,
"sigma_band_counts": {
"good": 20,
"watch": 4
},
"control_state_counts": {
"in_control": 21,
"watch": 2,
"out_of_control": 1
}
}
}

8. CI/CD Pipeline with All Tools (Complete Setup)

Recommended GitHub Actions workflow:

name: End-to-End Quality & Securityon: [push, pull_request]jobs:
quality:
runs-on: ubuntu-lateststeps:
- uses: actions/checkout@v3# Linting & style
- name: Lint with Pylintrun: | pip install pylint pylint guardrails/ core/ api/ tools/ --fail-under=9.0# Security scanning
- name: Bandit security scanrun: | pip install bandit bandit -r . -ll --exclude tests/# Dependency audit
- name: Check dependenciesrun: | pip install pip-audit pip-audit --fail-on high# Test execution
- name: Run testsrun: pytest --cov=guardrails --cov=core --cov-report=xml# Performance regression gate
- name: Run LoadRunner suiteif: env.LOADRUNNER_SCENARIO_ID != ''run: | echo "Trigger LoadRunner scenario $LOADRUNNER_SCENARIO_ID against /api/v1 endpoints"# Coverage upload
- name: Upload coverageuses: codecov/codecov-action@v3# Mutation testing (optional, slower)
- name: Mutation test guardrailsrun: | pip install mutmut mutmut run --paths-to-mutate=guardrails --tests-dir=tests# Quality gate (SonarQube)
- name: SonarQube analysisif: env.SONAR_HOST_URL != ''run: | pip install sonarscan sonar-scanner -Dsonar.host.url=${{ secrets.SONAR_HOST_URL }} \ -Dsonar.login=${{ secrets.SONAR_TOKEN }}

Testing Algorithm Matrix

Algorithm / TechniqueWhat It DoesWhere It Appears In This ProjectWhy It Improves Confidence
Topological sorting (Kahn)Orders dependent nodes safelytools/project_translator.py, tests/unit/test_topological_sort.pyPrevents subclass-before-base translation defects
Boundary value analysisHits min/max and edge inputstests/adversarial/test_boundary_conditions.pyFinds off-by-one and empty-input failures quickly
Equivalence partitioningTests one representative per input classGuardrail and malformed-input testsKeeps coverage broad without exploding test count
Decision-table testingCovers combinations of conditions and outcomesRBAC and forbidden-pattern testsEnsures policy combinations do not create gaps
State-transition testingVerifies behavior across state changesAudit trail blocked/allowed request scenariosConfirms system reacts correctly as request status changes
Cycle detectionDetects unsortable dependency graphstests/adversarial/test_circular_dependencies.pyVerifies graceful degradation on invalid project graphs
Mutation testingInjects fake bugs to measure test strengthDocumented via mutmut / Stryker integration pathConfirms tests fail when logic is wrong
Load testingMeasures latency and throughput under concurrencyLoadRunner integration and audit metricsProtects release readiness under realistic traffic
Risk-based prioritizationFocuses effort on highest-risk pathsNegative, adversarial, and auth testsKeeps security-critical paths heavily defended
Pairwise / combinatorial samplingReduces huge input combinations to meaningful pairsRecommended next step for API option matricesExpands coverage efficiently for future input flags

Six Sigma and Process Quality Matrix

Six Sigma IdeaMeaning In Plain TermsProject ImplementationEvidence / Metric
CTQ (Critical to Quality)The small set of outcomes that must go rightAudit records now track latency, reliability, safety, traceabilityctq_metrics in audit log
DMAICDefine, Measure, Analyze, Improve, Control loopREADME traceability + tests + audit metrics + quality gatesRequirements tables, tests, and audit trail
DPMODefects per million opportunitiesQuality snapshot computes DPMO per requestsix_sigma.dpmo in audit log
Control stateIs the process stable or drifting?Requests classified as in_control, watch, or out_of_controlsix_sigma.control_state
Performance control limitsExpected latency window before escalationPer-endpoint SLA budgets in env and audit metricsperformance_budget_ms, performance_status
FMEA mindsetRank likely failures before releaseNegative/adversarial suites focus on auth, injection, model lock, egressSecurity-focused test groups
Voice of customer / CTQ translationConvert user needs into measurable gatesREADME requirement tables map behavior to tests and toolingTraceability matrices
Continuous improvementUse data from each run to tighten the processAudit + coverage + static analysis + performance gatesCI pipeline and audit summaries

(back to top)

Scientific and Computer Science Algorithm Catalog

This section catalogs established computer science and mathematical algorithms that apply directly to the Java-to-Python translation pipeline, audit trail, guardrails, and quality metrics implemented in this project. Each algorithm is linked to the project area it improves.

Graph Theory and Dependency Analysis Algorithms

AlgorithmWhat It IsMost Common UseWhy It Should Be UsedHow It Helps This ProjectWhen Not To Use
Kahn's (implemented)In-degree based topological sort for DAGsBuild order resolution, dependency schedulingDeterministic ordering and clear cycle detection when no zero in-degree node remainsAlready used to order Java classes before translation so base classes are processed before dependentsNot for weighted path problems or graphs that are not DAG-like
Tarjan's SCCOne-pass DFS algorithm that finds all strongly connected componentsCycle grouping in directed graphs, compilers, package analyzersLinear-time cycle group discovery and reverse-topological SCC outputCan report all dependency cycles at once with grouped diagnostics for project translation failuresNot needed for tiny graphs where simple cycle-exists checks are enough
Kosaraju's SCCTwo-pass DFS SCC algorithm over graph and reversed graphSCC extraction when implementation simplicity is preferredEasy to reason about and verify for correctnessAlternate SCC implementation for cross-validating cycle group results from TarjanLess ideal when memory access to reverse graph is costly or graph is streaming
DFS/BFSFundamental graph traversals for depth or level explorationReachability, component discovery, shortest unweighted paths (BFS)Foundational and fast, useful in almost every graph pipelineDFS supports dependency walk and cycle heuristics; BFS can identify translation batches by levelNot enough alone when you need weighted optimization, SCC grouping, or formal ordering guarantees
DijkstraShortest-path algorithm for non-negative weighted graphsRouting, minimum cost path, critical path scoringFinds best path under weighted constraints efficientlyCan prioritize translation sequence by cost/risk weights (complexity, blast radius, module criticality)Not for negative edge weights, where Bellman-Ford style methods are required
Floyd-WarshallDynamic programming for all-pairs shortest pathsDense graph all-pairs analysis, transitive reachabilityGives full matrix visibility into every pair relationshipUseful for full dependency impact maps and change blast-radius analysisAvoid on large sparse graphs due to cubic cost
Union-FindDisjoint-set structure with union/find operationsConnectivity checks, incremental grouping, Kruskal-like workflowsVery fast near constant-time merges and membership checksCan speed incremental dependency ingestion and fast connectivity sanity checks before deeper analysisNot suitable for directed SCC semantics or ordered traversal outputs

Code Analysis and Transformation

AlgorithmWhat It IsMost Common UseWhy It Should Be UsedHow It Helps This ProjectWhen Not To Use
AST Traversal (implemented)Tree walk over parsed syntax nodesCompilers, linters, refactoring, static analyzersPreserves structural meaning better than regex parsingAlready powers Java structure extraction for classes/imports/method signaturesNot for runtime behavior reasoning without control/data flow context
Tree Edit Distance (Zhang-Shasha)Minimum edit cost between two treesAST diffing, clone analysis, migration similarity checksCaptures structural differences not visible in plain text diffCan score Java vs translated Python AST fidelity for stronger parity evidenceAvoid for very large trees in hot paths due to higher compute cost
CFGGraph model of possible execution paths in a function/methodDead code detection, path analysis, coverage planningExposes branch structure and reachability explicitlyCan verify translated Python keeps equivalent branch reachability vs JavaNot needed for simple straight-line code with no branching
Data-Flow AnalysisTracks definitions, uses, and propagation of values/typesCompiler optimization, bug finding, security checksDetects misuse and propagation mistakes earlyCan validate Java type/variable semantics survive mapping into PythonAvoid when analysis precision cost exceeds value for trivial modules
Program SlicingExtracts statements relevant to a variable/output criterionDebugging, comprehension, targeted verificationReduces analysis scope and noiseIsolates only code affecting a translated output to speed parity root-cause analysisNot ideal when holistic system interactions are the real issue
Taint Analysis (implemented conceptually)Marks untrusted input and tracks flow to sensitive sinksSecurity validation, injection preventionDirectly maps to security risk pathwaysSupports guardrail hardening by tracing untrusted request data through translation pipelineNot useful when all inputs are already trusted and isolated
Hindley-Milner Type InferenceUnification-based static type inferenceFunctional languages, inferred typing systemsImproves correctness with less manual annotationCould auto-suggest Python type hints from Java source semanticsNot a fit where dynamic/runtime types dominate behavior
Abstract InterpretationSound approximation of program states over abstract domainsStatic verification and bug class eliminationCan prove classes of errors without executing codeCan add formal assurance on translated output safety propertiesAvoid where exact concrete behavior is mandatory and approximation is too coarse

Pattern Matching and Security

AlgorithmWhat It IsMost Common UseWhy It Should Be UsedHow It Helps This ProjectWhen Not To Use
Aho-CorasickTrie + failure-link automaton for multi-pattern searchIDS signatures, malware scanning, keyword dictionariesFinds all patterns in one pass efficientlyCan replace sequential guardrail regex checks with one multi-pattern scanner for injection/secretsNot ideal for complex contextual patterns better handled by full parsers or regex engines
Rabin-KarpRolling-hash string matching approachPlagiarism/clone detection, multiple substring checksFast average matching and convenient window hashingCan detect repeated risky snippets or clone patterns across translated outputsAvoid when hash collision handling overhead or exact single-pattern speed is critical
Boyer-MooreHeuristic skip-based exact pattern matcherFast exact search in large textOften sublinear average performance for single patternUseful for fast scanning of one high-priority forbidden token/signatureNot for many patterns at once; Aho-Corasick is better there
Bloom FilterProbabilistic membership structure with false positives onlyCaching, prefiltering, dedupe prechecksVery memory-efficient and fast precheck stageCan fast-reject obviously safe payloads before expensive deep scansNot for workflows requiring zero false positives and exact membership
Levenshtein DistanceEdit-distance metric between stringsFuzzy matching, near-duplicate detection, typo toleranceQuantifies similarity robustlyCan score translation drift and flag suspiciously divergent output from expected behavior/textAvoid for strict semantic equivalence judgments without structural context

Formal Verification and Correctness

AlgorithmWhat It IsMost Common UseWhy It Should Be UsedHow It Helps This ProjectWhen Not To Use
Model CheckingExhaustive state-space verification against temporal propertiesProtocol verification, safety-critical policy checksFinds counterexamples rigorouslyCan prove RBAC and policy-lock invariants over request state transitionsAvoid for very large unconstrained state spaces without abstraction
Symbolic ExecutionExecutes paths with symbolic values and constraintsPath discovery, bug finding, test generationReaches edge paths hard to hit with manual testsCan generate adversarial API vectors to stress translation and guardrailsNot ideal when path explosion makes runtime impractical
Concolic TestingConcrete execution guided by symbolic constraintsAutomated test input generationPractical compromise between full symbolic and random testingCan expand coverage for translation endpoints with targeted boundary/path inputsAvoid when harness constraints are too expensive to maintain
Hoare LogicPre/postcondition proof framework for program correctnessFormal specs and proof-oriented correctnessSharp contractual reasoning around invariantsCan specify and verify required behavior for dependency ordering and policy checksNot needed where lightweight testing already provides enough assurance
Property-Based TestingRandomized input generation checked against invariantsInvariant testing and edge-case explorationFinds surprising cases that example-based tests missCan stress graph ordering and parity invariants over large random input spacesAvoid when properties are weakly defined or nondeterministic outputs are expected

Software Metrics

AlgorithmWhat It IsMost Common UseWhy It Should Be UsedHow It Helps This ProjectWhen Not To Use
McCabe Cyclomatic ComplexityBranch/path complexity metric from control flowTest planning and maintainability risk scoringCorrelates complexity with defect and testing effortCan drive risk-based test intensity on translated functions/classesNot as a sole quality signal without context
Halstead MetricsOperator/operand based software volume and effort metricsProductivity and maintainability analysisGives a language-agnostic complexity lensCan compare source vs translated code inflation and detect complexity bloatAvoid as hard pass/fail gates in isolation
Maintainability IndexComposite maintainability score from complexity/volume/LOCPortfolio-level code health trackingEasy high-level signal for triageCan prioritize translated files for manual review when score degradesNot reliable for very small files or generated code alone
Fan-In/Fan-OutCounts inbound and outbound dependency edgesArchitecture coupling analysisHighlights hotspots and blast-radius riskCan prioritize high fan-in classes for stricter parity and regression checksNot needed for tiny low-coupling modules

Audit and Statistical Process Control

AlgorithmWhat It IsMost Common UseWhy It Should Be UsedHow It Helps This ProjectWhen Not To Use
Shewhart Control Charts (implemented baseline)Control limits over time-series process metricsManufacturing and ops stability monitoringFast detection of obvious out-of-control behaviorAlready aligns to audit control-state tracking for latency/quality driftLess sensitive to small gradual drifts
CUSUMCumulative drift detector versus target meanEarly shift detection in process monitoringDetects subtle persistent changes earlier than ShewhartCan alert on slow latency degradation before SLA breachNot for highly non-stationary streams without segmentation
EWMAExponentially weighted moving average trend estimatorSmoothed monitoring and anomaly trend trackingBalances noise reduction with responsivenessCan provide cleaner quality/latency trendlines in audit dashboardsAvoid if abrupt shifts are the only concern and lag is unacceptable
Z-Score Anomaly DetectionStandard deviation based outlier scoringBasic anomaly and quality outlier flagsSimple, interpretable, low implementation costCan flag suspicious request records for investigation in near real-timeNot for heavy-tailed or non-Gaussian distributions without robust variants
Isolation ForestTree-ensemble unsupervised anomaly detectorFraud, operations anomalies, multivariate outliersCaptures nonlinear multivariate anomalies wellCan detect odd combinations of role, latency, block-rate, and payload characteristicsAvoid for tiny datasets where model instability is high
Bayesian InferencePosterior probability updating with evidenceRisk forecasting, decision support under uncertaintyIntegrates prior knowledge and new evidence rigorouslyCan estimate release risk from test outcomes plus historical defectsNot needed when deterministic thresholds are sufficient
Fisher's Exact TestExact significance test for contingency tablesSmall sample proportion comparisonsReliable p-values for low-count eventsCan test whether blocked-request spikes are statistically significantAvoid for large-sample cases where simpler approximations are fine

Test Coverage and Combinatorial

AlgorithmWhat It IsMost Common UseWhy It Should Be UsedHow It Helps This ProjectWhen Not To Use
IPOGCovering-array generator for t-way combinationsCombinatorial API/config test designLarge coverage gains with far fewer cases than full Cartesian productsCan systematically cover role x endpoint x payload combinations with manageable test countsNot necessary for very small parameter spaces
MC/DC CoverageCriterion requiring each condition independently affect outcomeSafety-critical software verificationStrong decision-logic assurance with efficient test setsCan harden guardrail and RBAC condition logic validationAvoid as universal requirement for low-risk modules due to overhead
Coverage-Guided FuzzingMutation fuzzing guided by code coverage feedbackSecurity hardening and crash discoveryEfficiently discovers deep parser/validation edge casesCan stress translation endpoints with malformed/adversarial Java inputsNot ideal where deterministic reproducibility and strict runtime budgets dominate
N-version/Differential TestingCompare outputs across independent implementationsCompiler/runtime verification and migration confidenceGreat at finding semantic mismatchesCan compare legacy Java oracle against translated Python outputs continuouslyNot useful if all compared implementations share same defect source

(back to top)

Legacy Java-to-Python Function Parity (Proof Tests)

The suite now includes proof-style parity tests that run the same function behavior in both legacy Java and translated Python and assert identical outputs for shared input vectors.

What Is A Vector, Vectoring, And A Vector Runner?

In this repository, a vector means one structured test case: input values plus the expected output.

Example vector concept:

  • Input: base=5, multiplier=10, premium=true
  • Expected output: 75

That single row is one vector. A vector file is a list of many such rows (normal, edge, and negative scenarios).

Vectoring is the testing approach where both runtimes (legacy Java and translated Python) are driven from that same shared vector dataset instead of hardcoded test values in multiple places.

Why vectoring is useful:

  • Single source of truth for migration parity expectations
  • Less duplicated test data across languages
  • Easier reviews and audits of behavioral requirements
  • Faster updates when business rules change

Vector Runner in this project:

  • LegacyCalculatorVectorRunner.java reads the shared JSON vectors
  • Executes the legacy Java function for each vector
  • Emits per-case output (id, actual, expected) for parity checks

This is how we prove output equivalence:

  1. Define vectors in shared JSON/CSV fixture files
  2. Run legacy Java against those vectors
  3. Run translated Python against those same vectors
  4. Assert Java output equals Python output for each vector id

This pattern gives an explicit migration proof: same inputs, same outputs, across runtimes.

Proof TestWhat It VerifiesLocation
Java fixture expected-value testLegacy Java behavior is stable and explicittests/correctness/test_legacy_java_python_equivalence.py
Python fixture expected-value testTranslated Python behavior matches intended outputstests/correctness/test_legacy_java_python_equivalence.py
Cross-language equivalence testJava output == Python output for the same inputstests/correctness/test_legacy_java_python_equivalence.py

Fixture sources:

  • fixtures/java/simple/LegacyCalculator.java
  • fixtures/java/simple/LegacyCalculatorVectorRunner.java
  • fixtures/expected_python/legacy_calculator.py
  • fixtures/vectors/legacy_calculator_vectors.json
  • fixtures/vectors/legacy_calculator_vectors.csv

Shared Vector Baseline (Single Source Of Truth)

AssetRuntime ConsumerPurposeStatus
legacy_calculator_vectors.jsonPython parity tests + Java vector runnerCanonical vector source (id, input, expected)Implemented
legacy_calculator_vectors.csvOptional import/export interoperabilitySpreadsheet-friendly mirror for manual reviewImplemented
LegacyCalculatorVectorRunner.javaJava runtimeReads shared JSON vectors and evaluates legacy functionImplemented
test_legacy_java_python_equivalence.pypytestParameterized cross-runtime parity assertionsImplemented

Tools That Already Support This Testing Pattern

ToolHow It Helps With Java-to-Python ParityTypical Use
pytest parameterized testsReuse the same vectors for both runtimesCore parity assertions (implemented)
JUnit 5 parameterized testsCapture legacy Java oracle outputsLegacy baseline generation (recommended next)
ApprovalTestsGolden-master snapshot comparisonsRegression lock for legacy outputs (recommended next)
JSON/CSV test vectorsRuntime-agnostic shared inputs/outputsSingle source of truth for parity data (implemented)
TestcontainersReproducible Java runtime executionStable local runtime parity in isolated containers (recommended next)

Practical recommendation: keep a shared vector file and run both Java and Python against it, treating Java output as the initial oracle during migration.

Zero-Trust Solutions Matrix

Zero-Trust ControlWhat It MeansProject ImplementationEvidence
Verify identity on every requestNo implicit trust by network locationJWT verification + RBAC dependency checks in API routestests/negative/test_rbac_enforcement.py
Explicit policy decision per requestEach request must be allow/deny evaluatedInput guardrails, model lock, egress policy lock, blocked audit pathtests/negative/test_model_blocking.py, tests/negative/test_egress_blocking.py, tests/adversarial/test_prompt_injection.py
Least privilege accessUsers only get required capabilitiesRole-permission mapping with permission-scoped endpointscore/auth.py, tests/negative/test_rbac_enforcement.py
Continuous verificationRuntime signals prove controls remain activeAudit report includes zero-trust rates, quality attestations, deny rate/api/v1/audit-report zero-trust section
Assume breach + contain blast radiusTreat unsafe inputs as hostile by defaultBlock injection/secret payloads and sanitize audit recordsguardrails/input_guard.py, guardrails/output_guard.py, tests/integration/test_audit_trail.py

The release dashboard now includes a dedicated zero_trust section with:

  • posture
  • identity_verification_rate
  • policy_decision_rate
  • continuous_verification_rate
  • policy_deny_rate

This makes zero-trust status measurable release-over-release instead of purely descriptive.

Requirements-to-Implementation Mapping

Requirement (README)Test (pytest)Security CheckQuality GateCoverage
"Guarantee base-before-subclass order"test_topological_sort.py (16 tests)Klocwork scanSonarQube: no high issues95%+ on project_translator.py
"Detect circular dependencies"test_circular_dependencies.py (4 tests)Bandit: no unsafe loopsNo tech debt on Kahn logic100% cycle path
"Block injection patterns"test_prompt_injection.py (5 tests)Klocwork CWE-89, CWE-95SonarQube security hotspots100% on input_guard patterns
"Redact secrets from output"test_forbidden_patterns.py (4 tests)Bandit hardcoding checkNo credential leak in logs100% on output_guard.redact()
"Enforce RBAC via JWT"test_rbac_enforcement.py (4 tests)Checkmarx token validationCrypto best practices100% on auth.py verify_token
"Policy lock for models/egress"test_model_blocking.py (3 tests)Klocwork: whitelist bypassNo bypass paths100% on provider_lock.py

This table is the top-to-bottom traceability matrix: each requirement has a test, security validation, and quality gate.

(back to top)

pie title Test File Distribution by Marker Group
"unit" : 5
"integration" : 4
"correctness" : 4
"negative" : 4
"adversarial" : 4
Loading
Marker GroupPurposeKey Benefit
unitAlgorithmic correctness for parsing/graph/orderFast feedback on core logic
integrationAPI request/response and contract validationCatches wiring and schema regressions
correctnessPython output structure and signature qualityProtects translation fidelity
negativePolicy and access-control enforcementPrevents unsafe execution paths
adversarialInjection and malformed input hardeningReduces attack-surface risk

(back to top)

Tool Compliance for Top Secret SCI/SCIF Regulated Environments

Classification Criteria:

  • 🟢 APPROVED: Tool is explicitly approved for classified/SCI work, has required security certifications (ISO 27001, FedRAMP, etc.), commonly used in defense/government sectors, or is open-source with minimal attack surface.
  • 🟡 CONDITIONAL: Tool can be used with specific restrictions (on-prem deployment only, special licensing, restricted data flow, etc.).
  • 🔴 NOT APPROVED: Tool lacks required certifications, uses unapproved cloud storage, transmits classified data externally, or has known security concerns for SCI environments.

Caution

All tools flagged as NOT APPROVED or CONDITIONAL must be reviewed by your security/compliance officer before use. Do not deploy tools flagged as NOT APPROVED in SCI/SCIF environments. CONDITIONAL tools require explicit variance/waiver documentation.

Core Runtime & Test Framework Dependencies

ToolVersionPurposeSCI/SCIF StatusRestrictions/Notes
Python3.11+Runtime interpreter🟢 APPROVEDOpen-source, widely used in government. Requires system-level deployment controls.
pytest8.0+Test framework🟢 APPROVEDOpen-source, MIT license. Standard in Python security testing. No external data transmission.
pytest-asyncio0.23+Async test support🟢 APPROVEDOpen-source, BSD license. Minimal attack surface.
httpx0.27+HTTP client for API testing🟢 APPROVEDOpen-source, BSD license. Used for in-process API testing only (no external calls).
FastAPI0.136+Web framework🟡 CONDITIONALOpen-source, MIT license. Requires hardened deployment configuration for SCI. Ensure all dependencies are audited. On-prem deployment only.
cryptography42.0+Cryptographic library🟢 APPROVEDOpen-source, dual Apache/BSD license. NIST-standard algorithms. Actively maintained.
PyJWT2.8+JWT signing/verification🟢 APPROVEDOpen-source, MIT license. Minimal, focused functionality.
Pydantic2.9+Data validation🟢 APPROVEDOpen-source, MIT license. No external validation calls. Widely adopted in security projects.
javalang0.13+Java parser🟢 APPROVEDOpen-source, BSD license. Local parsing only, no network access.

Static Analysis & Security Scanning Tools (SAST/SCA)

ToolPurposeSCI/SCIF StatusRestrictions/NotesRecommended?
Klocwork (Perforce)SAST - vulnerabilities, code quality🟢 APPROVEDEnterprise tool explicitly used by aerospace/defense. ISO 27001 certified. TÜV-SÜD certified. Commercial license required.YES - Preferred for classified environments
SonarQubeCode quality & maintainability🟡 CONDITIONALOn-prem deployment: APPROVED. Cloud (SonarCloud): NOT APPROVED. Requires air-gapped or internal-only instance.⚠️ On-prem only
Checkmarx (SAST)Enterprise vulnerability scanning🟢 APPROVEDExplicitly targets government/defense. Supports on-prem. Commercial license required.YES - Enterprise-grade SAST
Coverity (Synopsys)Deep static analysis🟢 APPROVEDDefense/aerospace standard tool. Commercial license required. Supports on-prem deployment.YES - Advanced static analysis
BanditPython-specific security scanning🟢 APPROVEDOpen-source, Apache 2.0 license. Lightweight, local execution only.YES - Lightweight pre-commit check
PylintPython linting & style🟢 APPROVEDOpen-source, GPL license. No external calls. Standard in Python ecosystem.YES - Pre-commit linting
pip-auditPython dependency vulnerability scanning🟢 APPROVEDOpen-source, MIT license. Local scanning, no remote calls by default.YES - Lightweight dependency audit
OWASP Dependency-CheckDependency vulnerability scanner🟢 APPROVEDOpen-source, Apache 2.0 license. Can run air-gapped with offline DB.YES - Comprehensive SCA
Black Duck (Synopsys)License & composition analysis🟡 CONDITIONALCommercial tool with on-prem option. Requires licensing agreement for classified use.⚠️ On-prem with variance
SnykDependency scanning SaaS🔴 NOT APPROVEDCloud-based SaaS. Data transmission to external service prohibited for SCI. Unapproved for classified use.NO - Do not use

Testing & Performance Measurement Tools

ToolPurposeSCI/SCIF StatusRestrictions/NotesRecommended?
pytest-covCode coverage measurement🟢 APPROVEDOpen-source, BSD license. Local execution only. Generates coverage reports.YES - Essential for V&V
CodecovCoverage tracking SaaS🔴 NOT APPROVEDCloud-based service. Transmits coverage data to external servers. Not approved for SCI environments.NO - Do not use
DatadogAPM & monitoring SaaS🔴 NOT APPROVEDCloud SaaS. Continuous data transmission to external servers. Classified data cannot be sent to Datadog.NO - Do not use
LoadRunner (Micro Focus/OpenText)Performance & load testing🟡 CONDITIONALOn-prem/self-hosted: APPROVED with proper security hardening. Cloud version: NOT APPROVED. Commercial license required.⚠️ On-prem only
StrykerMutation testing (Python/Java)🟢 APPROVEDOpen-source, Apache 2.0 license. Runs locally, no external calls.YES - Test quality verification
PITMutation testing for Java bytecode🟢 APPROVEDOpen-source, Apache 2.0 license. Local execution only.YES - For Java parity testing

Requirements Traceability & Test Management Tools

ToolPurposeSCI/SCIF StatusRestrictions/NotesRecommended?
TestRailTest management & traceability🟡 CONDITIONALSelf-hosted/on-prem: APPROVED with proper security controls. Cloud version: NOT APPROVED. Proprietary, commercial license.⚠️ On-prem with security review
Jira XrayTest management within Jira🟡 CONDITIONALOn-prem Jira: APPROVED. Cloud Jira: NOT APPROVED for SCI data. Proprietary plugin, commercial license.⚠️ On-prem only
Azure DevOps Test PlansRequirements & test traceability🟡 CONDITIONALOn-prem: APPROVED (requires Azure DevOps Server). Cloud (azure.com): NOT APPROVED for SCI.⚠️ On-prem only
ReqIF EditorRequirements interchange format🟢 APPROVEDOpen-source, EPL license. Local file-based tool, no external connections.YES - For requirements management

DevOps & Continuous Integration (CI/CD)

ToolPurposeSCI/SCIF StatusRestrictions/NotesRecommended?
GitHub ActionsCloud-hosted CI/CD🔴 NOT APPROVEDCloud-hosted service. Builds and artifacts transmitted to GitHub servers. Not approved for SCI code/data.NO - Use on-prem CI/CD
JenkinsOn-prem CI/CD automation🟢 APPROVEDOpen-source, MIT license. Can be air-gapped or on-prem only. Widely used in government.YES - Preferred CI/CD for SCI
GitLab CI (Cloud)Cloud-hosted CI/CD🔴 NOT APPROVEDCloud-hosted. Not approved for SCI code transmission.NO - Use on-prem option
GitLab CI (Self-Hosted)Self-hosted CI/CD🟡 CONDITIONALOn-prem deployment: APPROVED with proper air-gapping. Proprietary core, open-source options available.⚠️ On-prem with security review

Summary: Compliance Status by Category

CategoryApproved CountConditional CountNot Approved CountRecommendation
Core Dependencies8/810Use all core deps. Harden FastAPI deployment.
Static Analysis (SAST/SCA)5/922Use Klocwork, Checkmarx, Coverity as primary SAST. Avoid Snyk cloud.
Testing & Performance4/611Use pytest-cov and mutation testing. Avoid Codecov/Datadog cloud.
Requirements & Test Mgmt1/430Use ReqIF or on-prem TestRail/Jira. Avoid cloud services.
CI/CD1/412Use Jenkins on-prem. Avoid GitHub Actions and cloud CI.
TOTAL19/318/315/31Buildable with APPROVED tools. CONDITIONAL tools need variance.

Deployment Guidelines for SCI/SCIF Environments

For APPROVED Tools:

  • No additional review needed.
  • Deploy using standard security hardening practices.
  • Ensure all infrastructure is on-prem and air-gapped from external networks.

For CONDITIONAL Tools:

  • Requires security/compliance officer review and variance documentation.
  • Must be deployed on-prem (not cloud).
  • Ensure all data remains within security boundary.
  • Document any external dependencies or data transmission.

For NOT APPROVED Tools:

  • DO NOT DEPLOY in SCI/SCIF environments.
  • Seek alternative APPROVED tools.
  • Escalate to program security office if no alternative exists.

Migration Recommendations

If you are currently using NOT APPROVED tools:

Current ToolReason Not ApprovedAPPROVED Alternative
CodecovCloud SaaS, external data transmissionUse local pytest-cov + local artifact storage
DatadogCloud SaaS, continuous monitoringUse on-prem ELK, Grafana, or Prometheus stack
SnykCloud SaaS, external scanningUse OWASP Dependency-Check (on-prem) + Bandit
GitHub ActionsCloud CI/CDUse Jenkins on-prem or GitLab self-hosted
SonarCloudCloud SaaSUse SonarQube on-prem instance

(back to top)

Setup and Installation

Prerequisites:

  • Python 3.11+
  • Access to the orchestrator source path expected by conftest.py

Install:

python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Optional local env file:

cp .env.example .env

Quick validation:

pytest --collect-only -q

(back to top)

Usage

Run full suite:

pytest -q

Run by concern:

pytest -m unit -q
pytest -m integration -q
pytest -m correctness -q
pytest -m negative -q
pytest -m adversarial -q

Focused debugging flow:

  1. Install dependencies.
  2. Run the relevant marker group.
  3. Use -k to isolate failing behavior.
  4. Re-run the same slice to confirm regression closure.
pytest -m integration -k dependency_order -q

Tip

For long local runs, use Ctrl+C to stop gracefully and keep the latest failure summary.

(back to top)

Roadmap

gantt
title Verification Roadmap
dateFormat YYYY-MM-DD
section Core
Parser and ordering guarantees :done, r1, 2026-01-01, 2026-02-20
section Security
RBAC and guardrail hardening :active, r2, 2026-02-21, 2026-05-30
section Expansion
Coverage growth and mutation checks :r3, 2026-06-01, 2026-09-01
Loading
PhaseGoalsTargetStatus
CorePreserve dependency and translation order correctnessQ1 2026Complete
SecurityBroaden adversarial and RBAC scenariosQ2 2026In progress
ExpansionAdd mutation testing and richer fixture corporaQ3 2026Planned

(back to top)

Contributing

See CONTRIBUTING.md for workflow and test expectations.

Quality checklist for pull requests
  • Add or update tests for each behavior change.
  • Preserve dependency-order invariants in project translation paths.
  • Keep fixtures deterministic and security-safe.
  • Run targeted marker groups plus a full suite pass before opening a PR.

(back to top)

License

This project is licensed under the MIT License. See LICENSE for details.

(back to top)

About

Verification-first test infrastructure for secure, dependency-aware Java to Python translation services.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages