overgrowth / test_netbox.py
Graham Paasch
feat: Add NetBox/Nautobot SoT integration (Todo #1)
74f2bea
#!/usr/bin/env python3
"""
Test NetBox integration
Validates NetBox client and pipeline integration
"""
import logging
from pathlib import Path
from agent.netbox_client import NetBoxClient, NetBoxConfig
from agent.pipeline_engine import OvergrowthPipeline, NetworkIntent
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def test_netbox_mock_mode():
"""Test NetBox client in mock mode (no credentials)"""
print("\n=== Test 1: NetBox Mock Mode ===")
client = NetBoxClient()
assert client.mock_mode, "Should be in mock mode without credentials"
# Test site operations
site = client.create_site("test-site", "Test Site")
assert site["name"] == "test-site"
logger.info(f"βœ“ Created mock site: {site}")
# Test VLAN operations
vlan = client.create_vlan(vid=10, name="Management", description="Mgmt network")
assert vlan["vid"] == 10
logger.info(f"βœ“ Created mock VLAN: {vlan}")
# Test prefix operations
prefix = client.create_prefix("10.0.10.0/24", description="Mgmt subnet")
assert prefix["prefix"] == "10.0.10.0/24"
logger.info(f"βœ“ Created mock prefix: {prefix}")
print("βœ“ All mock mode tests passed\n")
def test_pipeline_with_netbox():
"""Test pipeline with NetBox integration"""
print("\n=== Test 2: Pipeline with NetBox ===")
# Create pipeline with NetBox enabled
pipeline = OvergrowthPipeline(use_netbox=True)
# Should be in mock mode without credentials
assert pipeline.netbox.mock_mode, "Should be in mock mode"
logger.info("βœ“ Pipeline created with NetBox client")
# Run through consultation and SoT generation
intent = NetworkIntent(
description="Small office network with 3 VLANs",
business_requirements=["Secure guest WiFi", "Isolated IoT devices"],
constraints=["Budget under $2000", "Easy management"],
budget="$2000",
timeline="2 weeks"
)
# Generate source of truth
model = pipeline.stage2_generate_sot(intent)
assert model.name is not None
assert len(model.vlans) > 0 or len(model.subnets) > 0
logger.info(f"βœ“ Generated network model: {model.name}")
logger.info(f" - VLANs: {len(model.vlans)}")
logger.info(f" - Subnets: {len(model.subnets)}")
logger.info(f" - Services: {model.services}")
print("βœ“ Pipeline integration test passed\n")
def test_network_sync():
"""Test syncing a complete network model"""
print("\n=== Test 3: Network Model Sync ===")
client = NetBoxClient()
# Create a sample network model
network_model = {
"name": "demo-network",
"description": "Demo network for testing",
"vlans": [
{"id": 10, "name": "Management", "purpose": "Network management"},
{"id": 20, "name": "Users", "purpose": "Employee workstations"},
{"id": 30, "name": "Guest", "purpose": "Guest WiFi"}
],
"subnets": [
{"network": "10.0.10.0/24", "vlan": 10, "purpose": "Management"},
{"network": "10.0.20.0/24", "vlan": 20, "purpose": "Users"},
{"network": "10.0.30.0/24", "vlan": 30, "purpose": "Guest WiFi"}
],
"devices": [
{"name": "core-sw-01", "model": "Cisco 9300", "role": "core"},
{"name": "access-sw-01", "model": "Cisco 2960", "role": "access"}
]
}
summary = client.sync_network_model(network_model)
logger.info(f"βœ“ Sync summary:")
logger.info(f" - Sites: {summary['sites']}")
logger.info(f" - Devices: {summary['devices']}")
logger.info(f" - VLANs: {summary['vlans']}")
logger.info(f" - Prefixes: {summary['prefixes']}")
if summary['errors']:
logger.warning(f" - Errors: {summary['errors']}")
print("βœ“ Network sync test passed\n")
def test_real_netbox_connection():
"""Test connection to a real NetBox instance (if configured)"""
print("\n=== Test 4: Real NetBox Connection (Optional) ===")
import os
if not os.getenv("NETBOX_URL") and not os.getenv("NAUTOBOT_URL"):
print("⊘ Skipping - No NetBox credentials configured")
print(" To test with real NetBox, set:")
print(" export NETBOX_URL=http://netbox.example.com")
print(" export NETBOX_TOKEN=your_api_token")
return
try:
client = NetBoxClient()
if client.mock_mode:
print("⊘ NetBox configured but connection failed - check credentials")
return
# Test basic operations
site = client.get_site("test-site")
logger.info(f"βœ“ Connected to NetBox at {client.config.url}")
if site:
logger.info(f" Found existing site: {site['name']}")
else:
logger.info(" No test site found")
print("βœ“ Real NetBox connection test passed\n")
except Exception as e:
logger.error(f"βœ— NetBox connection failed: {e}")
if __name__ == "__main__":
print("\n" + "="*60)
print("NetBox Integration Test Suite")
print("="*60)
try:
test_netbox_mock_mode()
test_pipeline_with_netbox()
test_network_sync()
test_real_netbox_connection()
print("\n" + "="*60)
print("βœ“ All tests completed successfully!")
print("="*60 + "\n")
except Exception as e:
print(f"\nβœ— Test failed: {e}")
import traceback
traceback.print_exc()
exit(1)