PLC_Generation/IO Tree Configuration Generator/test_sio_implementation.py
2025-08-05 14:38:54 +04:00

191 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""
Test script for SIO module implementation
========================================
Tests the SIO boilerplate model to ensure it works correctly with
IP address configuration and comment updates.
"""
import os
import sys
# Add the models directory to the path
sys.path.append(os.path.join(os.path.dirname(__file__), 'models'))
from models.sio_boilerplate_model import create_sio_module, SIOModuleGenerator
def test_sio_basic_functionality():
"""Test basic SIO module creation and configuration."""
print("Testing SIO module basic functionality...")
# Create a basic SIO configuration
config = create_sio_module(
name="SIO_TEST_1",
ip_address="192.168.1.100",
safety_input_names={
0: "Emergency Stop Line 1",
1: "Emergency Stop Line 2",
2: "Safety Gate Position",
3: "Light Curtain Active",
4: "Safety Mat Pressure",
5: "Reset Button Pressed",
6: "Enable Switch Active",
7: "Safety Scanner Zone"
},
safety_output_names={
0: "Main Safety Relay",
1: "Backup Safety Relay",
2: "Warning Light Red",
3: "Warning Light Amber",
4: "Safety Brake Release",
5: "Safety Brake Release",
6: "Safety Brake Release",
7: "Safety Brake Release"
}
)
# Create generator and apply updates
generator = SIOModuleGenerator(config)
try:
generator.load_boilerplate()
print(" ✓ Boilerplate loaded successfully")
generator.apply_updates()
print(" ✓ Updates applied successfully")
# Check that the IP address was updated
port = generator.root.find(".//Port[@Type='Ethernet']")
if port is not None and port.get("Address") == "192.168.1.100":
print(" ✓ IP address updated correctly")
else:
print(" ✗ IP address not updated correctly")
return False
# Check that module name was updated
module = generator.root.find(".//Module[@Use='Target']")
if module is not None and module.get("Name") == "SIO_TEST_1":
print(" ✓ Module name updated correctly")
else:
print(" ✗ Module name not updated correctly")
return False
# Check safety input comments
si_comments = generator.root.find(".//Connection[@Name='_200424962CC22C87']/InputTag/Comments")
if si_comments is not None:
comment_count = len(list(si_comments))
if comment_count == 8: # Should have 8 safety input comments
print(f" ✓ Safety input comments added ({comment_count} comments)")
else:
print(f" ✗ Expected 8 safety input comments, got {comment_count}")
return False
else:
print(" ✗ Safety input comments section not found")
return False
# Check safety output comments
so_comments = generator.root.find(".//Connection[@Name='_200424962C862CC2']/OutputTag/Comments")
if so_comments is not None:
comment_count = len(list(so_comments))
if comment_count == 5: # Should have 5 safety output comments
print(f" ✓ Safety output comments added ({comment_count} comments)")
else:
print(f" ✗ Expected 5 safety output comments, got {comment_count}")
return False
else:
print(" ✗ Safety output comments section not found")
return False
# Test saving the output
os.makedirs("generated", exist_ok=True)
output_path = "generated/SIO_TEST_1.L5X"
generator.save(output_path)
if os.path.exists(output_path):
print(f" ✓ SIO module saved successfully to {output_path}")
# Check file size to ensure it's not empty
file_size = os.path.getsize(output_path)
if file_size > 1000: # Reasonable size for XML file
print(f" ✓ Generated file has reasonable size ({file_size} bytes)")
else:
print(f" ✗ Generated file seems too small ({file_size} bytes)")
return False
else:
print(" ✗ Failed to save SIO module")
return False
return True
except FileNotFoundError as e:
print(f" ✗ Boilerplate file not found: {e}")
return False
except Exception as e:
print(f" ✗ Error during testing: {e}")
return False
def test_sio_minimal_config():
"""Test SIO module with minimal configuration."""
print("\nTesting SIO module with minimal configuration...")
# Create minimal configuration
config = create_sio_module(
name="SIO_MINIMAL",
ip_address="10.0.0.50"
)
generator = SIOModuleGenerator(config)
try:
generator.load_boilerplate()
generator.apply_updates()
# Verify basic properties
module = generator.root.find(".//Module[@Use='Target']")
port = generator.root.find(".//Port[@Type='Ethernet']")
if (module is not None and module.get("Name") == "SIO_MINIMAL" and
port is not None and port.get("Address") == "10.0.0.50"):
print(" ✓ Minimal configuration applied successfully")
return True
else:
print(" ✗ Minimal configuration failed")
return False
except Exception as e:
print(f" ✗ Error with minimal configuration: {e}")
return False
def main():
"""Run all SIO tests."""
print("Running SIO Module Implementation Tests")
print("=" * 40)
test_results = []
# Test basic functionality
test_results.append(test_sio_basic_functionality())
# Test minimal configuration
test_results.append(test_sio_minimal_config())
# Summary
print("\n" + "=" * 40)
passed = sum(test_results)
total = len(test_results)
if passed == total:
print(f"✓ All tests passed ({passed}/{total})")
print("SIO module implementation is working correctly!")
return 0
else:
print(f"✗ Some tests failed ({passed}/{total})")
print("Please check the SIO implementation.")
return 1
if __name__ == "__main__":
exit(main())